in reply to Checking for numbers and a period

It seems like you got it all down - so where is your question ?

I'll employ Psi::ESP and try to guess - you want to know how to check that a scalar contains a string that can be interpreted as a valid number - this is easy, as long as your definition of "number" is sane.

As you're talking about "price", I guess that your convention of "number" is "at least one digit from the range of 0 to 9, possibly followed by more such digits, possibly followed by a dot (to delimit the decimals), and then, if there was a dot, two more digits from the range 0 to 9".

After you've accepted this definition or have come up with your own definition, we need to translate this definition into a regular expression, since that's the easiest way of doing such things like conformance checks, as soon as you know regular expressions :

my $price = "100.09"; if ($price =~ / ^ # We begin at the start of the string [0-9]+ # At least one digit, possibly followed by more ( # Then (possibly, see below) follows \. # a dot [0-9][0-9] # and two more digits )? # But the decimal part is optional $ # And that's all there is to be /x) { } elsif { die "'$price' dosen't look like a valid price.\n" };

Update: Please do note that my guessed definition of "number" differs at least from BUUs definition of "number" below. It's not hard to come up with a solution that includes BUUs definition as well, but personally, I think a number should ALWAYS start with a digit from the range 0 to 9.

To add a support for the weird definition which allows a number to start with a period, use the following RE :

/^([0-9]+(\.[0-9]{2})?)|(\.[0-9]{2})$/
perl -MHTTP::Daemon -MHTTP::Response -MLWP::Simple -e ' ; # The $d = new HTTP::Daemon and fork and getprint $d->url and exit;#spider ($c = $d->accept())->get_request(); $c->send_response( new #in the HTTP::Response(200,$_,$_,qq(Just another Perl hacker\n))); ' # web

Replies are listed 'Best First'.
Re: Re: Checking for numbers and a period
by BrowserUk (Patriarch) on Jul 20, 2002 at 23:55 UTC

    For the sake of completness, we should also throw in numbers that start with a comma ",". Much of continental europe use number of the form 123 456,789 to be what we would normally right as 123,456.789

    Of course, if the number supplying audience includes a few mathematicians or science types, we might also encounter numbers such e^12 (where e=2.718... (or somethng)).

Re: Re: Checking for numbers and a period
by BUU (Prior) on Jul 20, 2002 at 23:13 UTC
    Only problem is it fails on ".23" =[

    The logical answer there is to do:
    /^\d*(\.\d\d)?$/;
    but of course that matches litterally everything. So good luck