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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |