in reply to Comparing undefined values

How about this:

( defined($p) ? '1' . $p : 0 ) eq ( defined($q) ? '1' . $q : 0 )

For example:

use strict; use warnings; my %strings = ( 'undef' => undef, 'empty' => '', 'string' => '0' ); my @pairs = ( [ 'undef' , 'undef' ], [ 'undef' , 'empty' ], [ 'undef' , 'string' ], [ 'empty' , 'empty' ], [ 'empty' , 'string' ], [ 'string', 'string' ], ); for ( @pairs ) { my ($p,$q) = @strings{@$_}; my $cmp = ( (defined($p) ? '1' . $p : 0) eq (defined($q) ? '1' . $q : 0) ) ? 'true' : 'false'; print join(" eq ", @$_), " = $cmp\n"; }

Result:

undef eq undef = true undef eq empty = false undef eq string = false empty eq empty = true empty eq string = false string eq string = true

-xdg

Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Replies are listed 'Best First'.
Re^2: Comparing undefined values
by Ovid (Cardinal) on Dec 16, 2005 at 21:50 UTC

    Great mind, great minds ... ;)

    Here's the test program I wrote:

    #!/usr/bin/perl -l use strict; use warnings; use Math::Combinatorics; my %v = ( undef => undef, empty => '', zero => 0, name => 'Ovid', ); my $combine = Math::Combinatorics->new( count => 2, data => [ keys %v ], ); while ( my ( $x, $y ) = $combine->next_combination ) { compare( $x, $y ); } foreach my $x ( keys %v ) { compare( $x, $x ); } sub compare { my ( $x, $y ) = @_; my ($X, $Y) = ($v{$x}, $v{$y}); print "\nComparing '$x' and '$y'"; no warnings 'uninitialized'; print +( ( defined $X == defined $Y ) && $X eq $Y ) ? "yes" : "no"; }

    Cheers,
    Ovid

    New address of my CGI Course.