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

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

    You often see the check for definedness so you don't have to deal with the warning for using an undef value (and in Perl 5.10 it tells you the offending variable):

     Use of uninitialized value $name in ...
    

    So, to get around this warning, people come up with all sorts of code, and that code starts to look like an important part of the solution rather than the bubble gum and duct tape that it is. Sometimes, it's better to show what you are doing by explicitly turning off the warning that you are trying to avoid:

     {
     no warnings 'uninitialized';
    
     if( length $name ) {
          ...
          }
     }
    

    In other cases, use some sort of null value instead of the data. With Perl 5.10's defined-or operator, you can give length an explicit empty string (defined, and give back zero length) instead of the variable that will trigger the warning:

     use 5.010;
    
     if( length( $name // '' ) ) {
          ...
          }
    

    In Perl 5.12, it's a bit easier because length on an undefined value also returns undefined. That might seem like a bit of silliness, but that pleases the mathematician I might have wanted to be. That doesn't issue a warning, which is the reason this question exists.

    use 5.012;
    use warnings;
    
    my $name;
    
    if( length $name ) { # no warning
        ...
        }
    

提交回复
热议问题