Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Using number "0" as an input argument

by Eily (Monsignor)
on Sep 22, 2015 at 08:57 UTC ( [id://1142710]=note: print w/replies, xml ) Need Help??


in reply to Using number "0" as an input argument

Actually you should check that the argument is defined instead of its truth, you can do either:
my $in1 = defined $ARGV[0] ? $ARGV[0] : ''; or my $in1 = $ARGV[0] // '';, I personally prefer to check that the number of arguments is correct first : my $in = (@ARGV > 0) ? shift : ''; (actually I often check the number of arguments first, so that I can ouput a warning when needed)
Note that after this point, $in1 will always be defined, because an undefined value will be replaced by the empty string (but 0 will be kept as is, and not turned to the empty string as in your code).

I don't know what you do exactly of your input, but I'm not sure you actually need the empty string when your argument is invalid, undef seems to be what you expect. There's of course more than one way to do it, so feel free to adapt this to your needs with a ternary operator, statment modifier or whatever will make this look better to you:

my $input = undef; if (@ARGV > 0 && $ARGV[0] !~ /\D/) { $input = shift; }

Edit: s/expecy/expect/ as pointed out by MidLifeXis :)

Replies are listed 'Best First'.
Re^2: Using number "0" as an input argument
by Doozer (Scribe) on Sep 22, 2015 at 09:20 UTC

    Sorry I should have given more info.

    The script takes 2 input arguments, both of which are numbers. The second argument is a time period in seconds so 0 will be an invalid choice.

    The first input argument which is the one that CAN be 0 is later used in the script as part of a system command input option (-Dhw:$in1).

Re^2: Using number "0" as an input argument
by mr_ron (Chaplain) on Sep 26, 2015 at 16:04 UTC

    If by "number" you mean an integer device number, the following technique for getting a list of results for regex captures should help. It is documented among other places here: http://perldoc.perl.org/perlrequick.html#Extracting-matches

    use warnings; use strict; my ($device) = defined($ARGV[0]) ? $ARGV[0] =~ /^\s*(\d+)\s*$/ : ''; print "Device #$device\n";
    Ron

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1142710]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-24 21:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found