开发者

How can I pass value to Perl Subroutine parameters on command line?

my test.pl script as below.

#!C:\Perl\bin\perl.exe
use stri开发者_运维百科ct;
use warnings;


sub printargs
{
    print "@_\n";
}

&printargs("hello", "world"); # Example prints "hello world"

If I replaced printargs("hello", "world"); with print($a, $b);.

How to pass 'hello' ,'world' to $a , $b when I run perl test.pl hello world at command line, Thanks.


Do read about @ARGV in perldoc perlvar.


$ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc.

$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1.


The command-line arguments are in the @ARGV array. Just pass that to your function:

&print( @ARGV );

Probably best to avoid a name like print - might get confused with the built-in function of the same name.


You want to access "command line parameters" in Perl.

Basically Perl sees the string you pass after the actual script name as an array named @ARGV.

Here is a brief tutorial: http://devdaily.com/perl/edu/qanda/plqa00001.shtml

Just google "perl command line parameters" for more.


Basically, as others said, the @ARGV list is the answer to your question.

Now if you want to go further and define command lines options for your programs, you should also have a loog at getargs.


This would also print "hello world" from the command line arguments while passing the data to $a and $b as requested.

#!/usr/bin/perl -w

use warnings;
use strict;

sub printargs($$)
{
    print $_[0] . " " . $_[1] . "\n";
}

my($a,$b) = ($ARGV[0],$ARGV[1]);
printargs($a,$b);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜