How can I assign a boolean condition result to a scalar variable in perl?

柔情痞子 提交于 2019-12-19 09:27:51

问题


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.

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


回答1:


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;

outputs 3.

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

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

outputs 1.



来源:https://stackoverflow.com/questions/17329142/how-can-i-assign-a-boolean-condition-result-to-a-scalar-variable-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!