1

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.

1
  • 3
    You would be wise to omit the & from &printargs(...). You don't need it and prefixing sub calls with & can have side-effects which you probably aren't expecting. Commented Feb 11, 2010 at 9:09

6 Answers 6

4

Do read about @ARGV in perldoc perlvar.

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

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

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.

1 Comment

Thank you. Revised print to printargs
1

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.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.