古詩詞大全網 - 四字成語 - perl接受傳遞參數的幾種方法

perl接受傳遞參數的幾種方法

1.使用壹個參數讀取shell傳遞來的多個參數:目錄下:

a.log

b.log

c.logdota.pldota.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 (<F) {

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

";}運行的shell如下:

find -name '*log' | /usr/bin/perl dota.pl -s -結果如下:file:a.logfile:b.logfile: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 =; $opt_a

" if $opt_a;

print "\$opt_b =; $opt_b

" if $opt_b;