Why does my Perl program print the help message when an arguments has 0 as a value?
Asked Answered
F

1

6

If i do this:

GetOptions(
    'u=s'    => \$in_username,
    'r=i'   => \$in_readonly,
    'b=i' => \$in_backup
    );

exit usage() unless $in_username && $in_readonly && $in_backup;

and call the program like this:

./app.pl -u david -r 12 -b 0

it always results in calling usage(), so obviously the 0 is not seen as an integer value. What can i do accept integer values AND 0?

Falkner answered 10/3, 2010 at 15:7 Comment(1)
Your statement "the 0 is not seen as an integer value" is correct but "0" is being interpreted as false: "A scalar value is interpreted as TRUE in the Boolean sense if it is not the null string or the number 0 (or its string equivalent, "0"). The Boolean context is just a special kind of scalar context where no conversion to a string or a number is ever performed." Dancrumb's answer is correct although not as explicit about your misstatement. perldoc.perl.org/perldata.htmlSwaggering
R
11

When treated as a boolean, 0 is considered to be a false value by Perl

You need something like

exit usage() unless defined($in_username) && defined($in_readonly) && defined(in_backup);

EDIT

Please also see msw's excellent comment to the original question

Rayshell answered 10/3, 2010 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.