Ovid has asked for the wisdom of the Perl Monks concerning the following question:
Perl has "convenient" behaviors which optimize away common cases for folks. Some of those deal with how undefined values are handled:
#!/usr/bin/perl -l use strict; my $x; print +($x eq '') ? 'Yes' : 'No';
That prints "yes", even though an undefined value is not the same as the empty string. Many times this is what you want, but not always. To get around this, the following verbose code will suffice:
#!/usr/bin/perl -l use strict; my $x; print +(defined $x && $x eq '') ? 'Yes' : 'No';
It gets much worse if you're comparing two variables:
if ( (not defined $new and not defined $old) or (defined $new and defined $old and $old eq $new) ) { ... }
Is there some way to get Perl to force a true comparison? (yes, I can wrap that in a sub or method, but I'd like a direct comparison)
Update: the following comparison is probably a bit faster but I doubt it's easier to read.
!( defined $x xor defined $y ) && $x eq $yCheers,
Ovid
New address of my CGI Course.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Comparing undefined values
by GrandFather (Saint) on Dec 16, 2005 at 20:39 UTC | |
by Ovid (Cardinal) on Dec 16, 2005 at 21:50 UTC | |
|
Re: Comparing undefined values
by xdg (Monsignor) on Dec 16, 2005 at 20:32 UTC | |
by Ovid (Cardinal) on Dec 16, 2005 at 21:50 UTC | |
|
Re: Comparing undefined values
by japhy (Canon) on Dec 16, 2005 at 19:46 UTC | |
by Ovid (Cardinal) on Dec 16, 2005 at 19:53 UTC | |
|
Re: Comparing undefined values
by ikegami (Patriarch) on Dec 16, 2005 at 20:52 UTC | |
|
Re: Comparing undefined values
by ikegami (Patriarch) on Dec 16, 2005 at 20:05 UTC | |
by QM (Parson) on Dec 16, 2005 at 23:27 UTC |