SPUG: PerlWTF?

John W. Krahn jwkrahn at shaw.ca
Fri Apr 9 17:45:41 PDT 2010


Andrew Sweger wrote:
> The Daily WTF doesn't show much love for Perl usually. Today I came across
> a doozy.
> 
> $x = ( $x > 1 ) ? $x-- : 0;
> 
> Granted, most of the time $x is undefined (naturally) and is just throwing
> warnings like crazy. It's the post-decrement that makes it so wonderfully
> nutty. I'd love to ask the original developer just what they were
> thinking. I'm replacing it with:
> 
> $x //= 0;
> $x-- if $x > 1;
> 
> Disclaimer: The names of some scalars were changed to protect the
> innocent.

They both don't do the same thing.

$ perl -le'
my $x; my $y;
$x = ( $x > 1 ) ? $x-- : 0;
$y //= 0;
$y-- if $y > 1;
print "\$x = $x  \$y = $y";
'
$x = 0  $y = 0

$ perl -le'
my $x = my $y = shift;
$x = ( $x > 1 ) ? $x-- : 0;
$y //= 0;
$y-- if $y > 1;
print "\$x = $x  \$y = $y";
'  -- -5
$x = 0  $y = -5

$ perl -le'
my $x = my $y = shift;
$x = ( $x > 1 ) ? $x-- : 0;
$y //= 0;
$y-- if $y > 1;
print "\$x = $x  \$y = $y";
'  -- 5
$x = 5  $y = 4

$ perl -le'
my $x = my $y = shift;
$x = ( $x > 1 ) ? $x-- : 0;
$y //= 0;
$y-- if $y > 1;
print "\$x = $x  \$y = $y";
'  -- 0
$x = 0  $y = 0

$ perl -le'
my $x = my $y = shift;
$x = ( $x > 1 ) ? $x-- : 0;
$y //= 0;
$y-- if $y > 1;
print "\$x = $x  \$y = $y";
'  -- ''
$x = 0  $y =


The correct expression would be:

$x = ( $x > 1 ) ? $x - 1 : 0;



John
-- 
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity.               -- Damian Conway


More information about the spug-list mailing list