in reply to Refactoring: dumb or witty use of ternary operator?

Howdy!

Interesting... Using perl 5.6.1 on solaris:

#!/home/mhough/perl/bin/perl use strict; use warnings; use Data::Dumper; my %outhash = (abc => 1, def => undef); my %outhash2 = %outhash1 print Dumper(\%outhash, \%outhash2); foreach my $str (qw/abc def ghi/) { $outhash{$str}? ($outhash{$str}++) : ($outhash{$str} = 1); $outhash2{$str}++; } print Dumper(\%outhash, \%outhash2);
yields:
$VAR1 = {
          'abc' => 1,
          'def' => undef
        };
$VAR2 = {
          'abc' => 1,
          'def' => undef
        };
$VAR1 = {
          'abc' => 2,
          'def' => 1,
          'ghi' => 1
        };
$VAR2 = {
          'abc' => 2,
          'def' => '1',
          'ghi' => '1'
        };

Note the subtle difference between key 'def' in the two cases. It would appear that autoincrement on an undef does the magical string autoincrement, leading to a string value of '1', while the code FatVamp offers sets a numeric value of 1.

What does it mean? I don't know, but the two forms do have ever so slightly different results whose difference probably doesn't matter.

yours,
Michael

Replies are listed 'Best First'.
Re^2: Refactoring: dumb or witty use of ternary operator? (1 not 3 copies)
by tye (Sage) on Jun 21, 2004 at 22:46 UTC

    If that matters to someone, they might consider something like:

    ++( $outhash{$str} ||= 0 );

    - tye        

Re^2: Refactoring: dumb or witty use of ternary operator?
by Roy Johnson (Monsignor) on Jun 21, 2004 at 22:45 UTC
    And if one were concerned, one could do
    $outhash{$str} += 1;
    to ensure numeric context.

    We're not really tightening our belts, it just feels that way because we're getting fatter.