ref="/tag/2034/" style="color:#874873;font-weight:bold;">Perl命令行参数的基本用法
在日常运维或脚本编写中,经常需要让程序根据不同的输入做出不同反应。Perl 作为老牌脚本语言,处理命令行参数非常灵活。最基础的方式是直接读取 @ARGV 数组,它保存了所有传入的参数。
#!/usr/bin/perl
print "参数数量: ", scalar(@ARGV), "\n";
print "第一个参数是: $ARGV[0]\n" if @ARGV;
比如运行 perl script.pl hello world,程序会输出参数个数和第一个值。这种写法简单直接,适合小型工具。
使用 Getopt::Std 管理短选项
当脚本功能变多,开始支持 -v、-f 这类开关时,手动解析就容易出错。Perl 自带的 Getopt::Std 模块可以帮你处理单字符选项。
#!/usr/bin/perl
use Getopt::Std;
my %opts;
getopts('vf:', \%opts);
if ($opts{v}) {
print "开启详细模式\n";
}
if (defined $opts{f}) {
print "文件名: $opts{f}\n";
}
上面这段代码支持 -v(布尔开关)和 -f(带参数的选项)。执行 perl script.pl -v -f config.txt 就能分别捕获这两个值。
更复杂的参数用 Getopt::Long
现代脚本往往需要 --input、--output 这样的长选项,这时候得靠 Getopt::Long。它是 CPAN 上的标准模块,功能强大。
#!/usr/bin/perl
use Getopt::Long;
my $input;
my $verbose = 0;
my @files;
GetOptions(
'input=s' => \$input,
'verbose|v' => \$verbose,
'files=s@' => \@files,
);
print "输入文件: $input\n" if $input;
print "详细模式已启用\n" if $verbose;
print "附加文件: ", join(', ', @files), "\n" if @files;
这里定义了三种类型:字符串(=s)、布尔值(带别名 v),以及数组(=s@)。传参时可以写成:perl script.pl --input data.txt -v --files a.txt --files b.txt,数组会自动收集多次出现的参数。
实际场景举例
假设你要写一个日志分析脚本,希望支持指定日期、是否发送邮件提醒、以及多个日志路径。用命令行参数就很方便:
#!/usr/bin/perl
use Getopt::Long;
my $date;
my $notify = 0;
my @paths;
GetOptions(
'date=s' => \$date,
'notify' => \$notify,
'path=s@' => \@paths,
);
$date //= `date -d yesterday +%Y-%m-%d`; chomp $date;
foreach my $path (@paths) {
open my $fh, '<', $path or warn "无法打开 $path: $!" and next;
while (<$fh>) {
print if /$date/;
}
close $fh;
}
if ($notify) {
system('echo "处理完成" | mail -s "日志报告" admin@example.com');
}
这样调用起来清晰明了:perl logscan.pl --date 2024-03-15 --notify --path /var/log/app.log --path /var/log/api.log,既灵活又易维护。