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
By convention, argv[0] is the command with which the program is invoked. argv[1] is the first command-line argument.
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.
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.
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)
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With