如何检查Perl标量变量是否已初始化? [英] How do I check if a Perl scalar variable has been initialized?

查看:257
本文介绍了如何检查Perl标量变量是否已初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是检查使用defined在Perl中是否初始化标量变量的最佳方法吗?

Is the following the best way to check if a scalar variable is initialized in Perl, using defined?

my $var;

if (cond) {
    $var = "string1";
}

# Is this the correct way?
if (defined $var) {
    ...
}

推荐答案

Perl不提供检查变量是否已初始化的方法.

Perl doesn't offer a way to check whether or not a variable has been initialized.

但是,未使用某些值显式初始化的标量变量在默认情况下恰好具有undef的值.您正确地认为defined是检查变量是否具有值undef的正确方法.

However, scalar variables that haven't been explicitly initialized with some value happen to have the value of undef by default. You are right about defined being the right way to check whether or not a variable has a value of undef.

还有其他几种方法.如果要分配给变量undef(示例代码似乎表明该变量),则可以使用perl的define-or运算符:

There's several other ways tho. If you want to assign to the variable if it's undef, which your example code seems to indicate, you could, for example, use perl's defined-or operator:

$var //= 'a default value';

这篇关于如何检查Perl标量变量是否已初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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