In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

前端 未结 9 911
名媛妹妹
名媛妹妹 2020-12-02 07:08

I currently use the following Perl to check if a variable is defined and contains text. I have to check defined first to avoid an \'uninitialized value\' warnin

相关标签:
9条回答
  • 2020-12-02 07:46

    In cases where I don't care whether the variable is undef or equal to '', I usually summarize it as:

    $name = "" unless defined $name;
    if($name ne '') {
      # do something with $name
    }
    
    0 讨论(0)
  • 2020-12-02 07:50
    if ($name )
    {
        #since undef and '' both evaluate to false 
        #this should work only when string is defined and non-empty...
        #unless you're expecting someting like $name="0" which is false.
        #notice though that $name="00" is not false
    }
    
    0 讨论(0)
  • 2020-12-02 07:52

    First, since length always returns a non-negative number,

    if ( length $name )
    

    and

    if ( length $name > 0 )
    

    are equivalent.

    If you are OK with replacing an undefined value with an empty string, you can use Perl 5.10's //= operator which assigns the RHS to the LHS unless the LHS is defined:

    #!/usr/bin/perl
    
    use feature qw( say );
    use strict; use warnings;
    
    my $name;
    
    say 'nonempty' if length($name //= '');
    say "'$name'";
    

    Note the absence of warnings about an uninitialized variable as $name is assigned the empty string if it is undefined.

    However, if you do not want to depend on 5.10 being installed, use the functions provided by Scalar::MoreUtils. For example, the above can be written as:

    #!/usr/bin/perl
    
    use strict; use warnings;
    
    use Scalar::MoreUtils qw( define );
    
    my $name;
    
    print "nonempty\n" if length($name = define $name);
    print "'$name'\n";
    

    If you don't want to clobber $name, use default.

    0 讨论(0)
提交回复
热议问题