Prateek
Prateek

Reputation: 159

Compare two (potentially) undef variables in perl

I am trying to compare two variables in which are usually strings. These variables are generated from a database, $var1 from one db and $var2 from another. When I compare them in a loop I use the ne operator. However there are times when I these variables are null or undef. The comparison is done as follows:

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

The issue is that if $var1 or $var2 are undef then I get an error. However, I need to be able to compare then values as undef b/c I will have to write them. I considered converting the variables to a string 'NULL' and then back but that seemed inefficient.

Any way to fix this? Thanks!

Upvotes: 13

Views: 11682

Answers (4)

mob
mob

Reputation: 118605

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.

Upvotes: 9

Joel Berger
Joel Berger

Reputation: 20280

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";
  }
}

Upvotes: 5

Tim
Tim

Reputation: 14154

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.

Upvotes: 14

aglassman
aglassman

Reputation: 2653

Use the defined function to determine this:

http://perldoc.perl.org/functions/defined.html

Upvotes: 0

Related Questions