in reply to Is there better way to delete dups in an AoH?

my %uniq = map { $_->{page} => 1 } @AoH; @AoH = map { { page => $_ } } keys %uniq;

This one would destroy all data that is not a value of the "page" key. But it solves the particular problem.

Replies are listed 'Best First'.
Re^2: Is there better way to delete dups in an AoH?
by bradcathey (Prior) on Jun 06, 2004 at 20:55 UTC
    Happy-the-monk, that was stunning! I love it when I can replace 15 lines of code with only 2. I plugged it in and worked like a charm.

    To be honest, I'm not sure how it works. My educated guess is it iterates through @AoH and assigns a key/value pair of page => 1 for every element. But why does it skip the 5th element (the dupe)? When I Dumper, I get:
    $VAR1 = 'fall'; $VAR2 = 1; $VAR3 = 'winter'; $VAR4 = 1; $VAR5 = 'spring'; $VAR6 = 1; $VAR7 = 'summer'; $VAR8 = 1;
    So, 1) why/how does it skip the dupe? 2) what does assigning the 1 do? 3) what does that 2nd line do to delete the key/value pairs of page => 1? Also, any good sources for learning how to disect a map/grep would be much appreciated. Thanks again.

    Update: Found this helpful resource in the meantime.

    —Brad
    "A little yeast leavens the whole dough."

      1) why/how does it skip the dupe?

      It actually doesn't skip it. It's just that it is assigned as a key to a hash, and hash keys are unique, thus it overwrites the old key without doing harm.

      2) what does assigning the 1 do?

      It's just a random value, you could assign anything you like as a value to the hash. It's not important, as long as there's something there to make perl happy.

      3) what does that 2nd line do to delete the key/value pairs of page => 1?

      nothing. It now restores the AoH. Hmm, I didn't tidy up the "%uniq" hash if you thought of that.

      Also, any good sources for learning how to disect a map/grep

      Besides   perldoc -f grep   and perldoc -f map? Hmm. Reading Perlmonks... ;)

      Cheers, Sören

        Thanks again for the excellent explanation. However, my script just got a bit more complicated. How do I get rid of two dupe keys per element? See what I naively tried:
        use Data::Dumper; use strict; my $AoH = [ { page => 'spring', chap => 'spring'}, { page => 'winter', chap => 'winter'}, { page => 'fall', chap => 'fall'}, { page => 'summer', chap => 'summer'}, { page => 'spring', chap => 'spring'} ]; my %uniq = map { $_->{page} => ; $_->{chap} => 1 } @$AoH; @$AoH = map { { page => $_ };{ chap=>$_ } } keys %uniq; print Dumper ($AoH);
        I doesn't work exactly the way it should and returns:
        $VAR1 = [ { 'chap' => 'summer' }, { 'chap' => 'winter' }, { 'chap' => 'fall' }, { 'chap' => 'spring' } ];

        —Brad
        "A little yeast leavens the whole dough."