About Linux FAQ

Browse More FAQs:

Perl display and pass command ling arguments with @argv

Posted by Vivek on Tuesday March 20, 07 @5:12 pm

Q. How do I read or display command-line arguments with Perl?

A. Perl command line arguments stored inn the special array called @ARGV.

ARGV example

Use $ARGV[n] to display argument.

Use $#ARGV to get total number of passed argument to a perl script.

For example if your scriptname is foo.pl and you called script as follows:

./foo.pl one two three

You can print one, two, three command line arguments with print command:
print "$ARGV[$0]\n";
print "$ARGV[$1]\n";
print "$ARGV[$2]\n";

Or just use a loop to display all command line args:

#!/usr/bin/perl -w
foreach $num (0 .. $#ARGV) {
	print "$ARGV[$num]\\n";
}

Here is an example (download link):

#!/usr/bin/perl -w
if ($#ARGV != 2 ) {
	print "usage: mycal number1 op number2\neg: mycal 5 + 3 OR mycal 5 - 2\\n";
	exit;
}
$n1=$ARGV[0];
$op=$ARGV[1];
$n2=$ARGV[2];
$ans=0;
if ( $op eq "+" ) {
	$ans = $n1 + $n2;
}
elsif ( $op eq "-"){
	$ans = $n1 - $n2;
}
elsif ( $op eq "/"){
	$ans = $n1 / $n2;
}
elsif ( $op eq "*"){
	$ans = $n1 * $n2;
}
else {
	print "Error: op must be +, -, *, / only\\n";
	exit;
}
print "$ans\\n";

Save and run script as follows:
$ chmod +x mycal.pl
$ ./mycal.pl
$ ./mycal.pl 5 + 3

Subscribe to our free e-mail newsletter or RSS feed to get all updates. You can Email this page to a friend.

Related Linux / UNIX FAQ:

Discussion on This FAQ

  1. kunal Says:

    Hi,
    i think u wrongly misspelled the spelling of line to ling in “Perl display and pass command ling arguments with @argv”

Leave a Reply

We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Please do not use the comment form to ask for help / question. Ask your question on the excellent Linux tech support forum. Thank you very much for stopping by our site!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

~ Last updated on: March 20, 2007

Copyright © 2006-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.