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

后端 未结 6 1846
日久生厌
日久生厌 2020-12-25 09:18

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

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

And also the same with the not equals operato

6条回答
  •  孤城傲影
    2020-12-25 09:42

    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).

提交回复
热议问题