parv has asked for the wisdom of the Perl Monks concerning the following question:
i find it odd that a no-regex-match would return anything but number 0, and always number 1 on match. i was expecting a 0 on non-match, but i got either undef or empty string. (my question is not why i get different values when used in list or scalar context.)
perl version is 5.6.1; below is the (tested) code to demonstrate the problem...
#!perl -w use strict; my $test; $test = 2; pr( 'no_zero' , $test , no_zero($test) ); # -> '1' pr( 'a_zero' , $test , a_zero($test) ); # -> '1' $test = 'pop'; pr( 'no_zero' , $test , no_zero($test) ); # -> 'undefined value' or '' pr( 'a_zero' , $test , a_zero($test) ); # -> '0' $test = undef; pr( 'no_zero' , $test , no_zero($test) ); # -> '' pr( 'a_zero' , $test , a_zero($test) ); # -> '0' sub no_zero { my $n = shift; my $re = qr/^ \d+ $/x; return #defined $n && $n =~ m/$re/ scalar( defined $n && $n =~ m/$re/ ) ; } sub a_zero { return no_zero( $_[0] ) || 0; } sub pr { my ($func , $val , $result) = @_; printf "%7s( '%s' ): '%s'\n" , ( $func , def($val) , def($result) ); sub def { my $v = shift; return ( (defined $v) ? $v : 'undefined value' ); } }
my overall goal was to use a sub like...
sub if_integer { my $i = shift; return defined $i && $i =~ m/^\d+$/; }
...i was surprised when instead of a false value got undefinded value when passed a defined and non-integer. i "solved" that problem by OR'ing w/ 0 which seems unnecessary...
return defined $i && $i =~ m/^\d+$/ || 0;
my question is why doesn't 0 is returned when m// fails, while 1 is returned on success?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: value returned on m// failure
by pg (Canon) on Dec 31, 2002 at 00:59 UTC | |
by parv (Parson) on Dec 31, 2002 at 01:33 UTC | |
by pfaut (Priest) on Dec 31, 2002 at 01:41 UTC | |
by parv (Parson) on Dec 31, 2002 at 05:15 UTC | |
by MarkM (Curate) on Dec 31, 2002 at 04:50 UTC | |
by parv (Parson) on Dec 31, 2002 at 05:41 UTC | |
by pg (Canon) on Dec 31, 2002 at 01:39 UTC | |
|
Re: value returned on m// failure
by BrowserUk (Patriarch) on Dec 31, 2002 at 01:03 UTC | |
by parv (Parson) on Dec 31, 2002 at 01:40 UTC |