in reply to What is the best way to determine if a string is blank?

There are three potential levels of 'blankness' that you should be checking for.

  1. Variable has never been given a value.
    Test with unless (defined $foo)
  2. Variable contains an empty string.
    Test with if ($foo eq '') (note that you could simplify it to unless ($foo) if you could be sure that zero wasn't a valid value.)
  3. Variable contains only whitespace.
    Test with if ($foo =~ /\S/)

Update Thanks to merlyn for pointing out the error in the second bullet point - which I've now corrected.

--
<http://www.dave.org.uk>

"Perl makes the fun jobs fun
and the boring jobs bearable" - me

  • Comment on Re: What is the best way to determine if a string is blank?

Replies are listed 'Best First'.
Re: Re: What is the best way to determine if a string is blank?
by isotope (Curate) on Jan 03, 2001 at 22:46 UTC
    Re Bullet 3:
    my $foo = " bar"; if($foo =~ /\S/) { print "Whitespace only\n"; }
    I think you meant:
    my $foo = " bar"; if($foo =~ /^\s+$/) { print "Whitespace only\n"; }
    Update: Whoops, davorg is right (see below)... and easier to see. I was thinking \s instead of \S. Fixed above, but hokey, so use his code instead.
    --isotope
    http://www.skylab.org/~isotope/

      Actually it should have been unless ($foo =~ /\S/) to maintain the same logic as the other examples.

      I think you may be confusing \s (whitespace) with \S (non-whitespace).

      --
      <http://www.dave.org.uk>

      "Perl makes the fun jobs fun
      and the boring jobs bearable" - me