如何将布尔条件结果分配给 perl 中的标量变量? [英] How can I assign a boolean condition result to a scalar variable in perl?

查看:41
本文介绍了如何将布尔条件结果分配给 perl 中的标量变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行以下操作,但无法正常工作:

I am doing the following, but it is not working properly:

    my $enabled = $hash && 
                  $hash->{'key'} && 
                  $hash->{'key'}->{'enabled'} && 
                  $hash->{'key'}->{'active'};

这是将布尔值分配给标量变量的可接受方式吗?我的代码以奇怪的方式行为不端,我相信这是因为这个任务.我已经验证了所有这些键都存在单独的值并设置为一个值.

Is this an acceptable way to assign a boolean value to a scalar variable? My code is misbehaving in strange ways, as it is, and I believe it is because of this assignment. I have validated that the individual values exist for all of these keys and are set to a value.

附:对不起,我是菜鸟!我用谷歌搜索了大约 10 分钟,但在任何地方都找不到答案.

P.S. Sorry for being a noob! I googled for ~10 minutes and couldn't find the answer anywhere.

推荐答案

Perl 布尔运算符,如 &&||and 不返回布尔值,它们返回其参数之一的值:

The Perl boolean operators like &&, ||, and, or don't return a boolean value, they return the value of one of their arguments:

say 2 && 3;

输出3.

您可以使用双重否定技巧将其强制为布尔值:

You can force it to a boolean with the double negation trick:

say !!(2 && 3);
# or
say not not 2 && 3;

输出1.

这篇关于如何将布尔条件结果分配给 perl 中的标量变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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