Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 456
Nick Bolton Avatar asked Jan 11 '10 23:01

Nick Bolton


People also ask

How do you check if a value is an empty string?

Use the length property to check if a string is empty, e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then it's empty, otherwise it isn't empty.

Is empty string false in Perl?

False Values: Empty string or string contains single digit 0 or undef value and zero are considered as the false values in perl.

How do I check if a string is in Perl?

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


2 Answers

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.

like image 127
Greg Hewgill Avatar answered Oct 12 '22 06:10

Greg Hewgill


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

like image 44
hobbs Avatar answered Oct 12 '22 07:10

hobbs