The following code may do what you want:
use strict;
use warnings;
my @pairs =
(
[undef, undef], [0, undef], [0, 0], ['', undef], ['', ''], [1, und
+ef], [1, 1],
[0, '0'], [0, 0], ['0', '0'], ['0e0', '0'], ['x', '0'], ['x', 0],
);
for (@pairs)
{
my @pair = (@$_);
print defined $pair[0] ? ">$pair[0]<" : 'undef';
print ', ' . (defined $pair[1] ? ">$pair[1]<" : 'undef');
print ': ' . (equals (@$_) ? "match\n" : "different\n");
}
sub equals {
my ($lhs, $rhs) = @_;
#False if mix of defined and undef
return 0 if defined $lhs != defined $rhs;
# True if both undef
return 1 if ! defined $lhs && ! defined $rhs;
# False if different as numbers
no warnings "numeric";
return 0 if (0 + $lhs) != (0 + $rhs);
# False if different as strings
return 0 if ('' . $lhs) ne ('' . $rhs);
return 1;
}
Prints:
undef, undef: match
>0<, undef: different
>0<, >0<: match
><, undef: different
><, ><: match
>1<, undef: different
>1<, >1<: match
>0<, >0<: match
>0<, >0<: match
>0<, >0<: match
>0e0<, >0<: different
>x<, >0<: different
>x<, >0<: different
DWIM is Perl's answer to Gödel
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.