Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: compare stdin for a number

by kesterkester (Hermit)
on Mar 12, 2004 at 20:34 UTC ( [id://336256]=note: print w/replies, xml ) Need Help??


in reply to compare stdin for a number

Something like this'll do (you'll probably want to wrap this in a loop to allow the user more than one try to get it right)
use warnings; use strict; chomp ( $_ = <> ); print "good input\n" if /^\d{5}$/;

Replies are listed 'Best First'.
Re: Re: compare stdin for a number
by Vautrin (Hermit) on Mar 12, 2004 at 21:00 UTC

    I know that the first time I was learning about regular expressions, "do ___" was much less helpful to me if it didn't include an explanation of why it should be done. I am including one here for completeness.

    The following code

    print "good input\n" if /^\d{5}$/;

    Should Could be rewritten:

    print "good input\n" if /^\d{5,5}$/;

    This is because {}s can contain 2 numbers seperated by a comma. The number on the left is the minimum number of the charachters (or things). The number on the right is the maximum number of charachters (or things). The charachter or thing is whatever is to the left of the {}s. So, \d{5,5} says 5 digits and only 5 digits, whereas \d{5} says at least 5 digits -- but possibly more. (Note that \d means a charachter that represents a number -- i.e. a digit)

    Of course, the reason the original regular expression will still work is the ^ and $ charachter mean "beginning of a line" and "end of a line", respectively. So my regular expression says "at least 5 digits but not more then 5 digits which start on the beginning of a line and end at the end of a line" while the original regular expression says "At least 5 digits between the beginning and end of a line -- and possibly more".

    Of course, the thing we have to pay attention to here is that mine would fail if we tried to match the string "Foo\n12345\nBar" This is because it fits all the constraints of the regular expression. However, because of the angle brackets <> -- which reads in a single line at a time, you know you can only have one line.

    Update: Thanks for pointing out my mistake Tom


    Want to support the EFF and FSF by buying cool stuff? Click here.
      /\d{5}/ means exactly 5(same as /\d{5,5}/).
      /\d{5,}/ means 5 or more.

      - Tom

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-24 20:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found