Search code examples
perlstringcomparison

What is the proper way to check if a string is empty in Perl?


I have been using this code to check if a string is empty:

if ($str == "")
{
  // ...
}

And also the opposite with the not equals operator...

if ($str != "")
{
  // ...
}

This seems to work (I think), but I'm not sure it's the correct way, or if there are any unforeseen drawbacks. Something just doesn't feel right about it.


Solution

  • For string comparisons in Perl, use eq or ne:

    if ($str eq "")
    {
      // ...
    }
    

    The == and != operators are numeric comparison operators. They will attempt to convert both operands to integers before comparing them.

    See the perlop man page for more information.