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 Corion (Patriarch)
on Sep 22, 2015 at 09:26 UTC ( [id://1142714]=note: print w/replies, xml ) Need Help??


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

I know I can validate that the input argument was there via the following bit of code:

chomp(my $in1 = $ARGV[0] || ''); if (defined $in1) { #Validate; }

Have you ever encountered a case where $in1 was not defined?

Maybe you want to directly check the number of arguments in @ARGV or look at what the || operator does?

Maybe the following code helps you analyze what happens better:

my $in1 = $ARGV[0] || 'user-did-not-pass-an-argument'); print $in1;

Run the above code with

perl -w myscript.pl # no argument perl -w myscript.pl "" # empty argument perl -w myscript.pl 0 # zero argument perl -w myscript.pl something-else # other argument

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

    Thanks for this. I just noticed I put "||" in my post instead of "//" which is what I have in my script. I know how they differ but thanks for pointing it out.

    I have now figured out it was a combination of using the // operator and also chomp. The code now looks something like:

    my $in1 = $ARGV[0]; chomp(my $in2 = $ARGV[1] // ''); if (defined $in1) { $in1 =~ s/\s+//g; # Remove all whitespace instead of chomp if ($in1 =~ /\D+/) { print "Input invalid. Only numbers are allowed\n"; } } else { print "No valid input given\n"; }
      $in1 =~ s/\s+//g;

      Although your comment suggests you are aware, I will still point out that s/\s+//g will remove all spaces, including spaces between digits/other characters, not just leading and trailing spaces.

      While unlikely to be a problem with your program, it is still possible to feed an unexpected value:

      yourprog "1 2"

      would result in $in1 being 12 and $in2 being empty

      This is why you should copy/paste code instead of retyping it in your post.

      Both more accurate and faster as well! :)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-19 17:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found