agoth has asked for the wisdom of the Perl Monks concerning the following question:

I was looking at the recipe of the day on Perl . Com and wondering how i would save the duplicate values when reversing a hash.

I was using the ternary syntax but it didnt work like I expected. Why does the second construct (without the braces) clobber the hash key with the value???

my %hash = ('apple2' => 'green', 'apple1' => 'green', 'banana' => 'yellow', 'plum' => 'red'); my %distinct; my %overflow; while (my ($k, $v) = each %hash) { # construct1 # (defined $distinct{$v}) ? ($overflow{$k} = $v) # : ($distinct{$v} = $k); # construct2 (exists $distinct{$v}) ? $overflow{$k} = $v : $distinct{$v} = $k; } for (keys %overflow) { print "$_, $overflow{$_} \n"; }

Replies are listed 'Best First'.
(tye)Re: Recipe of day - hashes q.
by tye (Sage) on Oct 16, 2000 at 22:00 UTC

    Go read perlop.pod. ?: binds tighter than = so the trailing = $k is outside the ?: construct.

    (exists $distinct{$v}) ? $overflow{$k} = $v : $distinct{$v} = $k;
    is
    ( (exists $distinct{$v}) ? $overflow{$k} = $v : $distinct{$v} ) = $k;
    which is like
    (exists $distinct{$v}) ? $overflow{$k} = $v = $k : $distinct{$v} = $k

    The correct way to resolve the precedence problem is:

    if( $distinct{$v} ) { $overflow{$k}= $v } else { $distinct{$v}= $k }
    (:

            - tye (but my friends call me "Tye")
Re: Recipe of day - hashes q.
by swiftone (Curate) on Oct 16, 2000 at 21:32 UTC
    Are you asking about the use of the ternary syntax, or the difference between exists and defined with hashes?

    Not part of your question, but I agree with a statement merlyn made: The ternary operator is good if you are using the value returned by it. If you are just using it to avoid an if, it obfuscates the code for no good reason.