Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

In the canonical solution for finding unique elements a hash is employed since the keys are guaranteed to be unique. You simply need two hashes; one top-level (snake, bird), and one deeper level (scales, fangs, tail). But then once you've used that deeper level hash to remove the duplicate attributes, you can convert its keys to the contents of an anonymous array referred to by the top-level hash. In other words, you can replace the lower level hash with an array containing the keys that lower level hash once held.

#!/usr/bin/env perl use strict; use warnings; use Data::Dumper; my %hash; while (<DATA>) { chomp; my ($k, $v) = split /\s/; $hash{$k}{$v} = undef; } $hash{$_} = [keys %{$hash{$_}}] for keys %hash; print Dumper \%hash; __DATA__ bird beak bird beak bird claw bird wings bird feathers snake fangs snake scales snake fangs snake tail

The output will be:

$VAR1 = { 'snake' => [ 'tail', 'fangs', 'scales' ], 'bird' => [ 'claw', 'wings', 'beak', 'feathers' ] };

Another approach could be to track whether an attribute pair has been seen before in realtime during the while loop, rather than postprocessing the hash of hashes into a hash of arrays. To do this you could use a temporary %attribseen hash where the keys are some unique concatenation of the animal type and a given attribute of that animal. For example, 'bird' and 'beak' could be used to form a hash key of bird|beak, and then you use that to assure uniqueness:

my %hash; { my %attribseen; while (<DATA>) { chomp; my ($k, $v) = split /\s/; push @{$hash{$k}}, $v unless $attribseen{"$k|$v"}++; } } print Dumper \%hash; __DATA__ bird beak bird beak bird claw bird wings bird feathers snake fangs snake scales snake fangs snake tail

The output will be the same as before. For some this may be simpler to look at. Even better (from a legibility standpoint) may be to separate out the uniqueness check into its own object, which can offer some internal state:

#!/usr/bin/env perl package PairUnique; use strict; use warnings; sub new {return bless {}, shift} sub unique { my ($self, $k, $v) = @_; return !$self->{"$k=>$v"}++ ? $v : (); } package main; use strict; use warnings; use Data::Dumper; my %hash; { my $get = PairUnique->new; while (<DATA>) { chomp; my ($k, $v) = split /\s/; my $aref = $hash{$k} //= []; push @$aref, $get->unique($k,$v); } } print Dumper \%hash; __DATA__ bird beak bird beak bird claw bird wings bird feathers snake fangs snake scales snake fangs snake tail

This separates out the uniqueness logic, and keeps only the structure-building logic inside the while loop. More code means more to maintain and understand, but it's possible that intent will be clearer to the person reading the code.


Dave


In reply to Re: assigning arrays as values to keys of hash by davido
in thread assigning arrays as values to keys of hash by pearllearner315

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others rifling through the Monastery: (10)
    As of 2019-07-22 12:37 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      If you were the first to set foot on the Moon, what would be your epigram?






      Results (17 votes). Check out past polls.

      Notices?