in reply to Regular Expression Help!

if a variable is empty and has only spaces

Strictly speaking a variable can be empty (value is undef) or contains only spaces:
if (defined $var or $var =~ /^\s+$/) { # $var is empty or contains only whitespace }
The \s actually tests for any white-space character, including tabs and new-lines.

Replies are listed 'Best First'.
Re^2: Regular Expression Help!
by johngg (Canon) on Jul 02, 2010 at 21:21 UTC
    a variable can be empty (value is undef)

    <nit>

    The string could be undefined or defined and contain a zero-length string before we move on to containing only spaces or some other text.

    $ perl -Mstrict -wE ' > sub grok > { > my $str = shift; > say > defined $str > ? $str > ? qq{>$str<: defined and true} > : qq{>$str<: defined but not true} > : qq{>$str<: undefined}; > } > > my $str; > grok( $str ); > $str = q{}; > grok( $str ); > $str = q{ }; > grok( $str ); > $str .= q{ABC}; > grok( $str );' Use of uninitialized value $str in concatenation (.) or string at -e l +ine 5. ><: undefined ><: defined but not true > <: defined and true > ABC<: defined and true $

    </nit>

    Cheers,

    JohnGG

Re^2: Regular Expression Help!
by Anonymous Monk on Jul 02, 2010 at 19:31 UTC
    but $var=""; and $var="data"; will both the in this IF, it doesn't work, I am trying to say if it is defined but empty move on.
      I think this will do it:
      if ( ($var =~ /^\s+$/) or ($var eq "") ){ print "\n All \n"; }else{ print "\n Nothing \n"; }
        I don't understand why you won't just use:
        if ($var =~ /^\s*$/) { # Do blank procedure } else { # Do nonblank procedure }
      I think this will do it:
      <code> if ( ($var =~ /^\s+$/) or ($var eq "") ){ print "\n All \n"; }else{ print "\n Nothing \n"; }