in reply to Validating Numbers in CGI Script?

The mysterious monk's advice is incomplete. Trying this approach from the command line shows the problem:
#!perl for $invalue (qw/ 1 -10 abc /) { eval{ local $^W = 1; $invalue + 0 }; ### Is Number? if ( $@ ) { print "$invalue is *not* a Number; Details: $@\n"; } else { print = "$invalue appears to be a number.\n"; } }
produces:
1 appears to be a number. -10 appears to be a number. Argument "abc" isn't numeric in add at num.pl line 3. abc appears to be a number.
The reason for this is that eval only traps errors, not warnings. The warning is printed directly to STDERR and $@ remains empty.

To fix this, you need to force the warning into an error. (And add an empty list assignment to silence the void context warning.):

#!perl for $invalue (qw/ 1 -10 abc /) { eval{ local $SIG{__WARN__} = sub { die @_ }; local $^W = 1; () = $invalue + 0 }; ### Is Number? if ( $@ ) { print "$invalue is *not* a Number; Details: $@\n"; } else { print "$invalue appears to be a number.\n"; } }
produces:
1 appears to be a number. -10 appears to be a number. abc is *not* a Number; Details: Argument "abc" isn't numeric in add at + num.pl line 4.

Replies are listed 'Best First'.
Re: Re: Validating Numbers in CGI Script?
by danger (Priest) on May 10, 2001 at 08:18 UTC

    Note, the new 'use warnings' pragma allows for various fine tuning of default and optional warnings -- including promoting any warning category into FATALs for a given lexical scope. So chipmunk's example can also be written as (assuming 5.6+):

    for $invalue (qw/ 1 -10 abc /) { eval{ use warnings FATAL=>qw/numeric/; $invalue + 0 }; ### Is Number? if ( $@ ) { print "$invalue is *not* a Number; Details: $@\n"; } else { print "$invalue appears to be a number.\n"; } }

    For details see the perllexwarn manpage, and the docs for the warning.pm module.