Re: String comparison operator trouble



Jürgen Exner wrote:
Dave B <daveb@xxxxxxxxxxxx> wrote:
J.D. Baldwin wrote:

next if ( undef $item )

$item == undef

This doesn't do what you seem to think it is doing.

Indeed, == forces a numeric context, so undef becomes 0. using 'eq'
interestingly seems to work (though, still with warnings - see below.)

First of all it will trigger two warnings (for generic $item):
- Use of uninitialized value in numeric eq (==) [*]
- Argument "...." isn't numeric in numeric eq (==) [**]


[*]: because undef is not initialized, surprise, surprise
[**]: because in the generic case $item may contain a string or -gasp-
be undefined instead of number.

I get a different set of warnings (using both 5.10.0 and 5.8.8)

$ perl5.8.8 -Mstrict -Mwarnings -we 'my $x = 1; print +($x == undef ?
"[undef]" : "[$x]"), "\n";'
Warning: Use of "undef" without parentheses is ambiguous at -e line 1.
Search pattern not terminated or ternary operator parsed as search
pattern at -e line 1.

I'm not sure where it's getting "Search pattern from, but I'm guessing
this has something to do with using (if ? then : else) instead of
if{}else{} ?


$ perl5.8.8 -Mstrict -Mwarnings -we 'my $x = 1; print +($x eq (undef)
? "[undef]" : "[$x]"), "\n";'
Use of uninitialized value in string eq at -e line 1.
[1]

$ perl5.8.8 -Mstrict -Mwarnings -we 'my $x = 0; print +($x eq (undef)
? "[undef]" : "[$x]"), "\n";'
Use of uninitialized value in string eq at -e line 1.
[0]

$ -Mstrict -Mwarnings -we 'my $x = undef; print +($x eq (undef) ?
"[undef]" : "[$x]"), "\n";'
Use of uninitialized value in string eq at -e line 1.
Use of uninitialized value in string eq at -e line 1.
[undef]

Of course, I wouldn't use this in any real code, and one should always
use defined($scalar) to test for defininty.

--
szr


.



Relevant Pages