Perl文件操作与命令行参数处理详解
1. getopt与getopts的区别
在处理脚本的命令行参数时,getopt和getopts是两个常用的工具。本质上,getopt不需要预先声明选项,但处理错误相对困难;而getopts需要声明选项,不过能更方便地处理错误。在大多数情况下,建议使用getopts,以避免进行大量的值测试。
2. 脚本示例:switches.pl
以下是一个简单的脚本示例,展示了如何根据不同的命令行开关对文件进行不同的处理。
#!/usr/bin/perl -w use strict; use Getopt::Std; use vars qw($opt_r $opt_l $opt_s $opt_n); if (! getopts('rlsn')) { die "Usage: switches.pl -rlsn\n"; } my @file = <>; if ($opt_s) { @file = sort @file; } if ($opt_n) { @file = sort {$a <=> $b} @file; } if ($opt_r) { @file = reverse @file; } my $i = 1; foreach my $line (@file) { if ($opt_l) { print "$i: $l