I expect the following code to behave the same whether using "normal" if or "ternary" ? : ; style if. But, I get different results. Can someone explain this?
use strict; use warnings; use Data::Dumper; my %lights; $lights{$_} = 0 for (1..4); foreach my $light ( sort { $a <=> $b } (keys %lights) ){ foreach my $divisor ( 2..4 ) { if ( $light % $divisor == 0 ) { # if it divides evenly, pu +ll the cord if ( $lights{$light} ) { $lights{$light} = 0; } else { $lights{$light} = 1; } } } } report({%lights}); # outputs 1 4 $lights{$_} = 0 for (1..4); foreach my $light ( sort { $a <=> $b } (keys %lights) ){ foreach my $divisor ( 2..4 ) { if ( $light % $divisor == 0 ) { # if it divides evenly, pu +ll the cord $lights{$light} ? $lights{$light} = 0 : $lights{$light +} = 1; # turn off if it's on, and vice versa. } } } report({%lights}); #outputs 1 sub report { my $lights = shift; print "off lights: "; foreach (sort { $a <=> $b }( keys %{$lights} ) ) { print "$_ " unless $lights->{$_}; } print "\n"; }
In reply to Ternary if versus normal if question by tphyahoo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |