On Monday 29 Mar 2010 17:10:27 Jeff Peng wrote:
> On Mon, Mar 29, 2010 at 10:02 PM, Jeff Soules <[email protected]> wrote:
> > Hi all,
> >
> > Am I missing something? I have the following chunks of code:
> >
> > EX 1:
> > if ($foo == 1){
> > $bar = 0;
> > }else{
> > $bar = 1;
> > }
> >
> > EX 2:
> > ($foo == 1) ?
> > $bar = 0 :
> > $bar = 1;
> >
> > These are logically equivalent, right?
>
> No. ($foo == 1) is a list which always has a value of either 1 or 0 so
> it really return a true value in both cases.
Not true:
{{{
shlomi:~$ perl -le '$foo = 0; print +($foo == 1) ? "Foo is 1" : "Foo is not
1"'
Foo is not 1
shlomi:~$ perl -le '$foo = 1; print +($foo == 1) ? "Foo is 1" : "Foo is not
1"'
Foo is 1
shlomi:~$
}}}
In the above case, I suggest rewriting it as either:
$bar = +($foo == 1) ? 0 : 1;
Or alternatively (and less ideally):
($foo == 1) ? ($bar = 0) : ($bar = 1);
(With parentheses.)
Of course in this particular case, this is equivalent to:
$bar = ($foo != 1);
Unless you care about $bar specifically being 0 instead of the also false
values of the empty-string or undef().
Regards,
Shlomi Fish
--
-----------------------------------------------------------------
Shlomi Fish http://www.shlomifish.org/
"Humanity" - Parody of Modern Life - http://shlom.in/humanity
Deletionists delete Wikipedia articles that they consider lame.
Chuck Norris deletes deletionists whom he considers lame.
Please reply to list if it's a mailing list post - http://shlom.in/reply .
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/