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!
One can compare it with NULL(in Java, PHP etc.) and Nil(in Ruby). So basically when the programmer will declare a scalar variable and don't assign a value to it then variable is supposed to be contain undef value. In Perl, if the initial value of a variable is undef then it will print nothing.
Just like other mathematical operators, instead of performing operations, these operators compare scalars. There are two types of sets of Perl comparison operators. Explanations for above Numeric and String Scalars Comparison Operators: == and eq: This operator is used to check the equality.
Perl | defined() Function Defined() in Perl returns true if the provided variable 'VAR' has a value other than the undef value, or it checks the value of $_ if VAR is not specified. This can be used with many functions to detect for the failure of operation since they return undef if there was a problem.
'eq' operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise equal to the string to its right.
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'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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With