Compare two (potentially) undef variables in perl

Check if they are defined, too:

foreach my $var1 (@$varlist)
    if ( ! defined $var1 || ! defined $var2 || $var1 ne $var2 )
        print "vars are not equal";

This prints that they're not equal if both are undefined. If you want another behaviour, just change the if expression.


It seems that you are practicing safe Perl by using use warnings; but now you may have come to the point where you selectively turn them off. These warnings are for your own protection, however if you know that you are going to be comparing possibly undef strings, just turn them off for a little bit (the no command is local to the enclosing block, so they turn back on).

use strict;
use warnings;

foreach my $var1 (@$varlist)
{
  no warnings 'uninitialized';
  if ($var1 ne $var2)
  {
    print "vars are not equal";
  }
}

It's not an error to compare undefined values, it's just a warning. I like using Perl's // operator (requires >=v5.10) in cases like this to ensure the operators are defined:

if (($var1 // '') ne ($var2 // '')) { ... }

will treat an undefined string as the empty string during the comparison, for example.

Since you want the operands to have a specific value when they are printed (NULL was one possibility), you could also consider using the //= operator.

if (($var1 //= 'NULL') ne ($var2 //= 'NULL')) {
   print "$var1 and $var2 are not equal";
}

will use the value of $var1 or $var2, or 'NULL' if they are undefined, in the comparison.

Tags:

Perl