我们在linux常常用到一个程序需要加入参数,现在了解一下perl中的有关控制参数的函数.getopt.在linux有的参数有二种形式.一种是–help,另一种是-h.也就是-和–的分别.–表示完整参数.-表示简化参数. 在perl中也分这二种. Getopt::Std模块的功能: 初始化perl命令行中所接受的参数,简化了命令行参数的解析。 简化参数例子: #!/usr/bin/perl -w use strict; use Getopt::Std; use vars qw($opt_a $opt_b $opt_c); getopts('a:b:c:'); #a: 这个冒号表示要有参数,不要冒号表示不要参数 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; 输出如下: [root@mail test]# ./getopt.pl -a aa -b bb -c cc $opt_a =>; aa $opt_b =>; bb $opt_c =>; cc 完整参数 #!/usr/bin/perl use Getopt::Long; Getopt::Long::GetOptions( ‘page=i’ => \$page, ‘onoff!’ => \$onoff, ‘help’ => \$wants_help, ‘name=s’ => \$name, ‘number:i’ => \$number); if(defined($page)){ print "page flag set to $page "; } if(defined($onoff)){ print "onoff flag set to $onoff "; } if(defined($wants_help)){ print "help flag set to $wants_help "; } if(defined($name)){ print "name flag set to $name "; } if(defined($number)){ print "number flag set to $number "; } ./getlong.pl -name AAA name flag set to AAA 带值参数 ※参数类型:整数, 浮点数, 字串 GetOptions( ‘tag=s’ => \$tag ); ‘=’表示此参数一定要有参数值, 若改用’:'代替表示参数不一定要有参数值 ’s’表示传递字串参数, 若为’i'表传递整数参数, 若为’f'表传递浮点数 example: test.pl –tag=string or test.pl –tag string 参数别名 GetOptions (’length|height=f’ => \$length); 第一个名称为primary name, 其他的名称为alias(可有多个alias名称) 当使用hash参数时, 使用primary name作为key值 参数的简称及大小写 GetOptions (’length|height=f’ => \$length, "head" => \$head); 若没有特别设定, Getopt会忽略参数的大小写, 也就是 -l or -L 指的都 是同一个参数(–length) 对于不传递参数的选项,也就是一些开关类型,可以在第一部分后接“!”,这表示该选项不接收自变量,但 是可以 通过在前面加上no变成负的(例如,“more”选项的-nomore)。如果不是用“!”,而是“+”,这表示它会在每次出现的时候增加一个变量。如果 选项出现在命令行里,那么相关的变量被设置为1;如果负的选项出现了,那么相关的变量就被设置为0。 例子3:命令行参数,读取一个目录下面的所有文件名 #result $opt_i_muscle_nex.sh #java CMDMuscle_clw_Format_nex /MK01_multi_dir_genus/*.clw MK01_multi_dir_genus/*.nex #perl muscle_clw_nex_shell.pl -d path -p #path MK01_multi_dir_genus #!/usr/bin/perl -w use strict; use Getopt::Std; use vars qw($opt_d $opt_p); getopts('d:p'); #$opt_i = "E:/MK01_multi_dir_genus"; my $outfile= "$opt_d"."_muscle_nex.sh"; my $filename=""; opendir (DIR,$opt_d) || die "Error in opening dir $opt_d\n"; while( ($filename= readdir(DIR))){ if($filename=~/[^\.]*\.clw/){ my $INfilename=$opt_d."/".$filename; my $muscle_nex = "java CMDMuscle_clw_Format_nex $opt_d/$filename $opt_d/$filename.nex"; print("$filename\n"); open(makeFile," >>$outfile" )or die " Couldn't open $! "; print makeFile "$muscle_nex\n"; } } closedir(DIR); close makeFile; print "complete"; 例子4:读取一个目录下面的所有文件 #!/usr/bin/perl use warnings; use strict; my %h=""; my $filename=""; my @arr=""; my $dirname="E:/Phyllostachys_edulis/PlnTF/"; opendir (DIR, $dirname)|| die "Error in opening dir $dirname\n"; while (($filename=readdir(DIR))){ next if $filename=~/^\./; open (FILE, "$dirname".$filename)|| die "can not open the file $filename\n"; while (<FILE>){ chomp; @arr=split/\s+/, $_; print "$filename\t$arr[0]\n"; } } |
评论