perl接受传递参数的几种方法

本文介绍两种Perl脚本中处理shell传参的方法:一种是通过指定参数读取文件列表,另一种是接收多个选项参数并打印。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 (<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\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 =>; $opt_a\n" if $opt_a;
print "\$opt_b =>; $opt_b\n" if $opt_b;
print "\$opt_c =>; $opt_c\n" if $opt_c;

/usr/bin/perl p1.pl -a aa -b bb -c cc
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值