Tomtom has asked for the wisdom of the Perl Monks concerning the following question:
Hello monks,
I have a question about perl syntax :
I know that this piece of code is the correct way to do what I need :
Does anyone have a good explanation ?
Thanks for your answers
I have a question about perl syntax :
I know that this piece of code is the correct way to do what I need :
but how comes the next piece of code ( which, in my opinion, would do the same thing ) doesn't work ? Could it be due to the exists function ( as suggested by a co-worker ) ? Here's the second piece of code :use strict; my %hash = ( 'A' => 'on', 'B' => 'on', 'C' => 'off', 'D' => 'off', 'E' => 'off', ); for (keys %hash) { my $result = (exists $hash{$_} and $hash{$_} eq 'on') ? 'OK' : 'KO'; print $result, "\n"; }
In the second sample, $result is assigned 'KO' everytime, and I just don't understand why.use strict; my %hash = ( 'A' => 'on', 'B' => 'on', 'C' => 'off', 'D' => 'off', 'E' => 'off', ); for (keys %hash) { my $result; (exists $hash{$_} and $hash{$_} eq 'on') ? $result = 'OK' : $result = 'KO'; print $result, "\n"; }
Does anyone have a good explanation ?
Thanks for your answers
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Question about ternary condition
by dave_the_m (Monsignor) on Jun 28, 2005 at 09:46 UTC | |
Re: Question about ternary condition
by robartes (Priest) on Jun 28, 2005 at 09:45 UTC | |
Re: Question about ternary condition
by fmerges (Chaplain) on Jun 28, 2005 at 10:13 UTC | |
Re: Question about ternary condition
by anonymized user 468275 (Curate) on Jun 28, 2005 at 09:42 UTC | |
by monarch (Priest) on Jun 28, 2005 at 11:15 UTC | |
by anonymized user 468275 (Curate) on Jun 28, 2005 at 11:34 UTC |
Back to
Seekers of Perl Wisdom