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

查看:112
本文介绍了在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 ) {
      ...
      }
 }

在其他情况下,请使用某种null值代替数据.使用 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中,这要容易一些,因为

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天全站免登陆