Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem passing 0 as command-line argument

I've just noticed a strange behavior of perl5 (5.10.0) when I passed 0 as the command-line argument to a script, which assigns it to a variable. The problem I encountered is that if I give the variable a default value in my script which is greater than 0, say 1, then I can pass any value except 0 to override the default value 1.

Following is the code of 'test.pl' I used:

#!/usr/bin/perl -w  
my $x = shift || 1;  
print "x is $x\n";  

Following are the commands and ouputs when I tested it:

$ ./test.pl 2  
x is 2  
$ ./test.pl 0  
x is 1  

I'd appreciate if anyone can shed light on this. Thanks. wwl

like image 754
Wayne Avatar asked Aug 18 '10 13:08

Wayne


People also ask

What is argv 0 in command line arguments?

By convention, argv[0] is the command with which the program is invoked. argv[1] is the first command-line argument.

Can you pass command line arguments?

To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.

How do I run a command line argument in CMD?

For example, entering C:\abc.exe /W /F on a command line would run a program called abc.exe and pass two command line arguments to it: /W and /F.


3 Answers

If you want $x to have the value of "1" in case no argument is provided, use this:

my $x = shift // 1;  

From perldoc perlop:

"//" is exactly the same as "||", except that it tests the left hand side's definedness instead of its truth.

Note: the defined-or operator is available starting from 5.10 (released on December 18th, 2007)

like image 52
Eugene Yarmash Avatar answered Sep 29 '22 20:09

Eugene Yarmash


The expression shift || 1 chooses the rhs iff the lhs evaluates to "false". Since you are passing 0, which evaluates to "false", $x ends up with the value 1.

like image 30
Marcelo Cantos Avatar answered Sep 29 '22 20:09

Marcelo Cantos


The best approach is the one in eugene's and Alexandr's answers, but if you're stuck with an older perl, use

my $x = shift;
$x = 1 unless defined $x;

Because you have a single optional argument, you could examine @ARGV in scalar context to check how many command-line arguments are present. If it's there, use it, or otherwise fall back on the default:

my $x = @ARGV ? shift : 1;
like image 25
Greg Bacon Avatar answered Sep 29 '22 22:09

Greg Bacon