For Programmers: Free Programming Magazines  


Home > Archive > PERL Programming > February 2005 > check if two possibly undef values differ









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author check if two possibly undef values differ
Nils Boysen

2005-02-02, 8:55 am

hi,

what is the simplest way to compare two values that might be undef
preserving undef?

I want to preserve undef so I can't use ($x || '') && ($y || '')

the simplest way I could come up with is this:

#!/usr/bin/perl -w

use strict;

my $x = undef;
my $y = undef;

if((defined $x && !defined $y) || (!defined $x && defined $y)
|| (defined $x && defined $y && $x ne $y)) {
print "differ\n";
}

there has to be a way to write this simpler - is there?

thanx.
Roar Sunde

2005-02-03, 3:56 pm

On 2005-02-02, Nils Boysen <nils@boysen.info> wrote:
> hi,
>
> what is the simplest way to compare two values that might be undef
> preserving undef?
>
> I want to preserve undef so I can't use ($x || '') && ($y || '')
>
> the simplest way I could come up with is this:
>
> #!/usr/bin/perl -w
>
> use strict;
>
> my $x = undef;
> my $y = undef;
>
> if((defined $x && !defined $y) || (!defined $x && defined $y)
> || (defined $x && defined $y && $x ne $y)) {
> print "differ\n";
> }
>
> there has to be a way to write this simpler - is there?
>
> thanx.


This should do it.

{
local $SIG{'__WARN__'} = sub {};
print "differ\n" unless $x eq $y;
}

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com