Question

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.

Was it helpful?

Solution

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

OTHER TIPS

Do read about @ARGV in perldoc perlvar.

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top