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

前端 未结 9 950
名媛妹妹
名媛妹妹 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: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.

提交回复
热议问题