---
title: "perl接受传递参数的几种方法"
author: "forrest420"
date: "2011-09-29T16:12:24Z"
tags: ["Perl"]
categories: ["编程语言"]
slug: "perl"
draft: false
lastmod: "2011-09-29T16:12:24Z"
id: 1183309
url: "https://forrest420.iteye.com/blog/1183309"
---

1.使用一个参数读取shell传递来的多个参数: 目录下： a.log b.log c.log dota.pl dota.pl的内容如下: #! /usr/bin/perl use Getopt::Std; use warnings; use strict; sub read\_from\_sh($) { my $file = shift; my @files = (); open F, $file or die "Could not open $file: $!"; while () { next if /^\\s\*$/; push @files, $\_; } close F or die "Could not close $file: $!"; return @files; } my @files; my %opts = (); getopts("s:", \\%opts); if ($opts{'s'}) { @files = read\_from\_sh($opts{'s'}); }else { @files = @ARGV; } for my $file (@files) { print "file: $file\\n"; } 运行的shell如下: find -name '\*log' | /usr/bin/perl dota.pl -s - 结果如下： file:a.log file:b.log file:c.log 或者直接塞给perl：/usr/bin/perl dota.pl a.log b.log 结果同上 2.向perl程序传递多个参数： #!/usr/bin/perl -w use strict; use Getopt::Std; use vars qw($opt\_a $opt\_b $opt\_c); getopts('a:b:c:'); print "\\$opt\_a =&gt;; $opt\_a\\n" if $opt\_a; print "\\$opt\_b =&gt;; $opt\_b\\n" if $opt\_b; print "\\$opt\_c =&gt;; $opt\_c\\n" if $opt\_c; /usr/bin/perl p1.pl -a aa -b bb -c cc