在 Perl 中,如何简洁地检查 $variable 是否已定义并包含非零长度字符串? [英] In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

查看:11
本文介绍了在 Perl 中,如何简洁地检查 $variable 是否已定义并包含非零长度字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用以下 Perl 来检查变量是否已定义并包含文本.我必须先检查 defined 以避免未初始化的值"警告:

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' warning:

if (defined $name && length $name > 0) {
    # do something with $name
}

有没有更好(大概更简洁)的方式来写这个?

Is there a better (presumably more concise) way to write this?

推荐答案

您经常会看到对定义性的检查,因此您不必处理使用 undef 值的警告(并且在 Perl 5.10 中它会告诉您有问题的变量):

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 ) {
      ...
      }
 }

在其他情况下,使用某种空值而不是数据.使用 Perl 5.10 的定义或运算符,你可以给 length 一个明确的空字符串(定义,并返回零长度)而不是将触发警告的变量:

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 // '' ) ) {
      ...
      }

在 Perl 5.12 中,它更容易一些,因为 length 在未定义的值上也会返回 undefined.这可能看起来有点愚蠢,但这让我可能想成为的数学家感到高兴.那不会发出警告,这就是这个问题存在的原因.

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
    ...
    }

这篇关于在 Perl 中,如何简洁地检查 $variable 是否已定义并包含非零长度字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆