使用argV

时间:2015-10-23 10:37:41

标签: perl command-line command-line-arguments perl-module

如何在Perl中使用命令行参数从用户输入文件?可能像:wxp.pl - file {file path} 我是Perl的新人,所以建议我一些有用的东西。我怎样才能让它像在命令行中询问一样多一个参数。 例如:

exp.pl -file {file path}
           -x    {it's arg}
           -y    {y's arg}

3 个答案:

答案 0 :(得分:2)

如果简单,你想要传递参数,你可以这样做:

perl exp.pl arg1 agr2

如果您想要更多内容,请使用Getopt::Long模块。

答案 1 :(得分:1)

我建议GetOpt :: Long来实现这一目标。但是如果你想让自己看看这样的话会不方便:

use strict;
use warnings;

# Usage check. For "perl xxx.pl -a arg1 -b arg2" args. should be even nos. 

if (scalar @ARGV == 0 or scalar @ARGV % 2 != 0) {
    print "Usage:\n\t$0 -a arg1 -b arg2 requires all args\n";
    exit 0;
}

# This one convert cmd line args. to hash ex. (perl xxx.pl -a arg1 -b arg2) to {-a => arg1, -b => arg2}
my %argHash = @ARGV;    

# Optional but see if all the args are present
my $maxArgs = 2;
if (scalar keys %argHash != $maxArgs) {
    print "Usage:\n\t$0 -a arg1 -b arg2 requires exactly $maxArgs args\n";
    exit 0;
}

# Parse arguments. 
print "$0:\n";
for my $key (keys %argHash) {
    print "\t $key: $argHash{$key}\n";  
}

1;

结果:

c:\swadhi\perl>perl cmdline.pl
Usage:
        cmdline.pl -a arg1 -b arg2 requires all args

c:\swadhi\perl>perl cmdline.pl -a "user" -b
Usage:
        cmdline.pl -a arg1 -b arg2 requires all args

c:\swadhi\perl>perl cmdline.pl -a "user" -b "Command"
cmdline.pl:
         -a: user
         -b: Command

c:\swadhi\perl>perl cmdline.pl -a "user" -b "Command" -c "mock"
Usage:
        cmdline.pl -a arg1 -b arg2 requires exactly 2 args

c:\swadhi\perl>perl cmdline.pl -a "user"
Usage:
        cmdline.pl -a arg1 -b arg2 requires exactly 2 args

答案 2 :(得分:1)

更简单的GetOpt ::长版

use strict;
use warnings;
use Getopt::Long qw(GetOptions);

my $user_name;

GetOptions('user=s' => \$user_name) or die "Usage: $0 --user NAME\n";

if ($user_name) {
    print  $user_name, "\n";
}

结果:

c:\swadhi\perl>perl cmdline.pl -user Swadhi
Swadhi

c:\swadhi\perl>perl cmdline.pl

c:\swadhi\perl>perl cmdline.pl -p s
Unknown option: p
Usage: cmdline.pl --user NAME

c:\swadhi\perl>perl cmdline.pl -u "This should also work"
This should also work