Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Quicker way to do this IF statement 1-5

by varian (Chaplain)
on May 20, 2007 at 08:05 UTC ( [id://616403]=note: print w/replies, xml ) Need Help??


in reply to Quicker way to do this IF statement 1-5

A regex solution can be short and elegant:
if ($b=~/^[1-5]$/) { print "\$b has to be a number and is either 1, 2, 3, 4, or 5.\n"; }

Replies are listed 'Best First'.
Re^2: Quicker way to do this IF statement 1-5
by Anonymous Monk on May 20, 2007 at 09:16 UTC
    The correct regex solution :)
    /^[1-5]\z/
      To say that using "\z" is "the correct regex solution" (and imply that using "$" is "incorrect") is a bit silly, esp. in the absence of more detailed info regarding the application.

      There are some situations where the two solutions will have different behaviors, and in such cases, it's up to the programmer to decide which is more appropriate. Either one could be more useful (or "correct") than the other, depending on the task. But in many common situations, they behave the same, and neither is "more correct" than the other.

        To say that using "\z" is "the correct regex solution" (and imply that using "$" is "incorrect") is a bit silly, esp. in the absence of more detailed info regarding the application.

        If, as the OP requested, the variable must contain an integer between 1 and 5 inclusive, "1\n" seems like an invalid option. Unfortunately, /^\d$/ gives a false positive for that value.

        But in many common situations, they behave the same...

        I can only think of one case, and that's where the string does not have a trailing newline.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2024-04-25 05:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found