Re: Better expression for $x = !!$y||0
by pelagic (Priest) on Apr 19, 2005 at 08:14 UTC
|
$x = $y ? 1 : 0;
and: timtowtdi ...
| [reply] [d/l] |
|
$x = int !!$y;
| [reply] [d/l] |
|
| [reply] [d/l] |
Re: Better expression for $x = !!$y||0
by reasonablekeith (Deacon) on Apr 19, 2005 at 08:53 UTC
|
quote:
I rewrote this to:
if ( $x = !!$y || 0 ) {
...
}
...
I'm sorry, but that's just awful. I'd never guess what you were actually trying to do here if I stumbled across this code, regardless of how correct it might be.
In my opinion there's not much wrong with your first example, and although the conditional operator does add some brevity, the if else construct is almost certainly more readable to more people.
| [reply] [d/l] |
Re: Better expression for $x = !!$y||0
by Anonymous Monk on Apr 19, 2005 at 09:26 UTC
|
I'd go for $y ? 1 : 0. Other suggestions, like !!$y || 0 or 1 - !$y may not return 0 or 1 if $y has overload magic.
It also doesn't require the reader to know that negating a false value returns 1 (and not some other true value). | [reply] [d/l] [select] |
Re: Better expression for $x = !!$y||0
by ysth (Canon) on Apr 19, 2005 at 09:00 UTC
|
Shorter: $x = 1-!$y
Better, IMO, but much depends on what the reader knows about x and y from the surrounding code: $x = 0;
if ($y) {
$x = 1;
...
}
| [reply] [d/l] [select] |
|
Like others in this thread, you too are presuming the sanity of the ! return. In fact, ! can return 37 for true. There's no promise in the Perl docs otherwise.
| [reply] |
|
I said shorter, I didn't say accurate :). But really, if you presume an overloaded ! that returns something other than perl's true and false values (and that's presuming an awful lot) there's nothing you can do to $y besides examine it in boolean context with if or ?:.
| [reply] |
|
|
|
|
Re: Better expression for $x = !!$y||0
by salva (Canon) on Apr 19, 2005 at 13:11 UTC
|
for maximum readibility and if you are doing this kind of conversion in more than one place, you can also create a new "booleanize" operator:
sub booleanize ($) { shift ? 1 : 0 }
$x = booleanize $y;
| [reply] [d/l] |
Re: Better expression for $x = !!$y||0
by prasadbabu (Prior) on Apr 19, 2005 at 08:12 UTC
|
| [reply] [d/l] |
|
Not properly this (typo?). The other reply is correct ($x=$y?0:1)
| [reply] |
Re: Better expression for $x = !!$y||0
by ghenry (Vicar) on Apr 19, 2005 at 08:18 UTC
|
See the Conditional Operator, to understand the above better.
Walking the road to enlightenment... I found a penguin and a camel on the way.....
Fancy a yourname@perl.me.uk? Just ask!!!
| [reply] |
|
Thanks all,
sure I know about the conditional. It just look unnatural in a if statement to me. Thats why I used || in the first place. But since all answers are more or less the same. I shouldn't be so picky.
| [reply] |
|
$x = $y ? 1 : 0;
if ($x) {
...
}
It has the added advantage of removing an assignement from an if's condition, something I find quite unnatural and unreadable.
| [reply] [d/l] [select] |