views:

291

answers:

6

Hi. my test.pl script as below.

#!C:\Perl\bin\perl.exe
use strict;
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.

+2  A: 

$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.

Pieter
You can also just use @ARGV to get the number of elements.eg: if (@ARGV < 2) { die "Usage: " . $0 . " <param>\n"; }
+1  A: 

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.

p.marino
+2  A: 

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.

martin clayton
Thank you. Revised *print* to *printargs*
Nano HE
A: 

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.

kriss
+4  A: 

Do read about @ARGV in perldoc perlvar.

Sinan Ünür
A: 

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);