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

PerlStringComparison

Perl Problem Overview


I've just been using this code to check if a string is empty:

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

And also the same 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.

Perl Solutions


Solution 1 - Perl

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.

Solution 2 - Perl

  1. Due to the way that strings are stored in Perl, getting the length of a string is optimized.
    if (length $str) is a good way of checking that a string is non-empty.

  2. If you're in a situation where you haven't already guarded against undef, then the catch-all for "non-empty" that won't warn is if (defined $str and length $str).

Solution 3 - Perl

You probably want to use "eq" instead of "==". If you worry about some edge cases you may also want to check for undefined:

if (not defined $str) {

# this variable is undefined

}

Solution 4 - Perl

As already mentioned by several people, eq is the right operator here.

If you use warnings; in your script, you'll get warnings about this (and many other useful things); I'd recommend use strict; as well.

Solution 5 - Perl

The very concept of a "proper" way to do anything, apart from using CPAN, is non existent in Perl.

Anyways those are numeric operators, you should use

if($foo eq "")

or

if(length($foo) == 0)

Solution 6 - Perl

To check for an empty string you could also do something as follows

if (!defined $val || $val eq '')
{
    # empty
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick BoltonView Question on Stackoverflow
Solution 1 - PerlGreg HewgillView Answer on Stackoverflow
Solution 2 - PerlhobbsView Answer on Stackoverflow
Solution 3 - PerlDmitryKView Answer on Stackoverflow
Solution 4 - PerlMatthew SlatteryView Answer on Stackoverflow
Solution 5 - PerlwhatsisnameView Answer on Stackoverflow
Solution 6 - PerlRoland AyalaView Answer on Stackoverflow