为什么我的Perl排序程序失败了?

时间:2014-09-15 05:37:43

标签: perl sorting

我有一个Perl程序的assignemt,它将在命令行中获取字符串,并将它们打印回来排序,并使用-r或--reverse命令开关进行反向排序。排序部分工作,但当我调用-r它会丢弃其中一个字符串。

perl Bagwell_Assign_One.plx -r c b a

b a

# Sort and Unsort
#Zak Bagwell
#The purpose of this program is to take strings as command line arguments and sort
#invoke by: perl filename.plx string string string 
# -r will output reverse order sort


use 5.8.8;
use strict;
use Getopt::Std;  # use for the -r reverse sort
use vars qw($opt_r);  # use for the -r reverse sort
use vars qw($opt_reverse); # use for the -reverse sort

getopts('r:');  # use for the -r reverse sort


if ($#ARGV < 1) {  # a test for strings is preformed first
  print "Invalid command line arguments to program. Please supply two or more strings to sort.\n";
  die  "\n";
  } #end if


elsif (defined $opt_r){ # if -r is present, the sort is reversed 

  @ARGV = reverse sort(@ARGV);
  }

elsif (defined $opt_reverse){ # if -reverse is present, the sort is reversed  

  @ARGV = reverse sort(@ARGV);
  }


else {  # if no -r, then normal sort
  @ARGV = sort @ARGV;
  } #end else


# Display output 
print "@ARGV\n";

那么,我做错了什么?我的教授几乎没有给我反馈......

1 个答案:

答案 0 :(得分:4)

下面的冒号告诉Getopt::Std -r标志带有一个参数:

getopts('r:');                # use for the -r reverse sort

要修复,只需删除冒号:

getopts('r');                # use for the -r reverse sort

为了进一步简化,我建议只使用Getopt::Long代替所有此类项目。

它会自动处理长选项名称的缩写。因此-r可以用作--reverse的别名,只要没有任何其他选项以字母R开头。

use strict;
use warnings;

use Getopt::Long;

GetOptions(
    "reverse" => \( my $opt_reverse ),
) or die "Error in command line arguments\n";

die "Invalid command line arguments to program. Please supply two or more strings to sort.\n"
    if @ARGV < 2;

@ARGV = sort @ARGV;
@ARGV = reverse @ARGV if $opt_reverse;

print "@ARGV\n";