为什么以下代码显示错误?

时间:2016-11-09 06:50:07

标签: perl perl-module getopt getopt-long

我想从命令行传递参数,所以我尝试了以下代码,但是它会抛出错误?

use strict;
use warnings;
use Getopt::Long qw(GetOptions);
use Getopt::Std;
print "raw data:@ARGV\n";
my $site=getopts('bangalore','norwood','limerick');
if($site)
{
print "success";
}
else
{
die "error";
}
print "final data:@ARGV \n";

2 个答案:

答案 0 :(得分:1)

您的代码不正确。请先阅读文档:http://perldoc.perl.org/Getopt/Long.html

下面是试图猜测你想要实现的目标。

use strict;
use warnings;
use Getopt::Long qw(GetOptions);
my $city;
print "raw data:@ARGV\n";
GetOptions ("city=s" => \$city) or die("Error in command line arguments\n");
my $site = $city;
if($site){
    print "success: City is $city\n";
}
print "Final data:@ARGV \n";

输出:

chankeypathak@stackoverflow:~/Desktop$ perl test.pl -city=bangalore
raw data:-city=bangalore
success: City is bangalore
Final data: 

传递错误的参数时的输出:

chankeypathak@stackoverflow:~/Desktop$ perl test.pl -blah=blah
raw data:-blah=blah
Unknown option: blah
Error in command line arguments

答案 1 :(得分:0)

Thanks to: alvinalexander

#!/usr/bin/perl -w

# a perl getopts example
# alvin alexander, http://www.devdaily.com

use strict;
use Getopt::Std;

# declare the perl command line flags/options we want to allow
my %options=();
getopts("hj:ln:s:", \%options);

# test for the existence of the options on the command line.
# in a normal program you'd do more than just print these.
print "-h $options{h}\n" if defined $options{h};
print "-j $options{j}\n" if defined $options{j};
print "-l $options{l}\n" if defined $options{l};
print "-n $options{n}\n" if defined $options{n};
print "-s $options{s}\n" if defined $options{s};

# other things found on the command line
print "Other things found on the command line:\n" if $ARGV[0];
foreach (@ARGV)
{
  print "$_\n";
}