How can I pass command-line arguments to a Perl pr

2019-01-04 22:26发布

I'm working on a Perl script. How can I pass command line parameters to it?

Example:

script.pl "string1" "string2"

9条回答
Explosion°爆炸
2楼-- · 2019-01-04 22:52

Yet another options is to use perl -s, eg:

#!/usr/bin/perl -s

print "value of -x: $x\n";
print "value of -name: $name\n";

Then call it like this :

% ./myprog -x -name=Jeff
value of -x: 1
value of -name: Jeff

Or see the original article for more details:

查看更多
女痞
3楼-- · 2019-01-04 22:57

You can access them directly, by assigning the special variable @ARGV to a list of variables. So, for example:

( $st, $prod, $ar, $file, $chart, $e, $max, $flag ,$id) = @ARGV;

perl tmp.pl 1 2 3 4 5

enter image description here

查看更多
太酷不给撩
4楼-- · 2019-01-04 22:57

If the arguments are filenames to be read from, use the diamond (<>) operator to get at their contents:

while (my $line = <>) {
  process_line($line);
}

If the arguments are options/switches, use GetOpt::Std or GetOpt::Long, as already shown by slavy13.myopenid.com.

On the off chance that they're something else, you can access them either by walking through @ARGV explicitly or with the shift command:

while (my $arg = shift) {
  print "Found argument $arg\n";
}

(Note that doing this with shift will only work if you are outside of all subs. Within a sub, it will retrieve the list of arguments passed to the sub rather than those passed to the program.)

查看更多
聊天终结者
5楼-- · 2019-01-04 22:57
my $output_file;

if((scalar (@ARGV) == 2) && ($ARGV[0] eq "-i"))

{

$output_file= chomp($ARGV[1]) ;


}
查看更多
做个烂人
6楼-- · 2019-01-04 23:00
foreach my $arg (@ARGV) {
    print $arg, "\n";
}

will print each argument.

查看更多
倾城 Initia
7楼-- · 2019-01-04 23:01

Depends on what you want to do. If you want to use the two arguments as input files, you can just pass them in and then use <> to read their contents.

If they have a different meaning, you can use GetOpt::Std and GetOpt::Long to process them easily. GetOpt::Std supports only single-character switches and GetOpt::Long is much more flexible. From GetOpt::Long:

use Getopt::Long;
my $data   = "file.dat";
my $length = 24;
my $verbose;
$result = GetOptions ("length=i" => \$length,    # numeric
                    "file=s"   => \$data,      # string
                    "verbose"  => \$verbose);  # flag

Alternatively, @ARGV is a special variable that contains all the command line arguments. $ARGV[0] is the first (ie. "string1" in your case) and $ARGV[1] is the second argument. You don't need a special module to access @ARGV.

查看更多
登录 后发表回答