Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top