[VPM] detecting non-integers

Michael S. Joyce michael at negativespace.net
Tue May 6 22:24:16 CDT 2003


I don't think that will work the way you expect. The match will succeed for 
anything with a digit in it, giving you erroneous results. I tested your 
regular expression from the command line:
[20:17:58][e] $perl -nle 'print qq(yes\n) if(m/^-?\d+\.?\d*$/);'
10
yes

100
yes

100.00
yes

You can see that it matches the 10, when it shouldn't. The problem is that 
? matches zero or one times, and * matches zero or more times. And matching 
zero times is considered a successful match.

I think a better way to do it would be to reverse the logic somewhat.

unless($xfgAmount =~ /^\d+$/) {
         print $cgi->p("Please enter the funds as a whole number in cents. 
\$1.00 = 100 cents.");
         print $cgi->end_html;
         exit 1;
}

Please let me know if I've missed anything, or if I've helped.

Michael

At 09:39 AM 05/06/2003 -0700, you wrote:
>*On Mon May 05, 2003 at 04:47:33PM -0700, Malcolm Dew-Jones 
>(yf110 at victoria.tc.ca) wrote:
> >
> >
> >
> > On Mon, 5 May 2003, Carl B. Constantine wrote:
> >
> > > Since perl doesn't have types as such, what is the best way to detect
> > > this, just a regex like: =~/\d+(\.)*/ or is there an easier way?
> >
> > A regex is the most typical way.  I would show some but I hate to do that
> > without testing them cause it's so easy for something to not work quite as
> > you expect.  Well may be just one, the simplist
>
>Yes, regex works just fine. A private email from Draco Paladin quoted a
>perlfaq4 entry that had what I needed, which is simply:
>
>if ($xfrAmount =~ /^-?\d+\.?\d*$/ ) {
>   print $cgi->p("Please enter the funds as a whole number in cents. 
> \$1.00 = 100 cents.");
>   print $cgi->end_html;
>   exit 1;
>}
>
>Thanks everyone for your help....again! ;-)
>
>--
>Carl B. Constantine         University of Victoria
>Programmer Analyst          http://www.csc.uvic.ca
>UNIX System Administrator   Victoria, BC, Canada
>cconstan at csc.uvic.ca        ELW A220, 721-8753




More information about the Victoria-pm mailing list