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;
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;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询