Reputation: 5958
I have a little problem with some hashes.
if i have a hash containing, John,John,John,Bob,Bob,Paul - is there then a function that can return just:
John, Bob, Paul.
In other words i want to get all different values(or keys if value is not possible) - but only once :).
I hope u understand my question, thx :)
Upvotes: 0
Views: 1718
Reputation: 37156
TIMTOWTDI:
my @unique = keys { reverse %hash };
Note the performance caveat with reverse
though:
This operator is also handy for inverting a hash, although there are some caveats. If a value is duplicated in the original hash, only one of those can be represented as a key in the inverted hash. Also, this has to unwind one hash and build a whole new one, which may take some time on a large hash, such as from a DBM file.
%by_name = reverse %by_address; # Invert the hash
Upvotes: 3
Reputation: 67920
De-duping is easily (and idiomatically) done by using a hash:
my @uniq = keys { map { $_ => 1 } values %hash };
A simple enough approach that does not require installing modules. Since hash keys must be unique, any list of strings become automatically de-duped when used as keys in the same hash.
Note the use of curly braces forming an anonymous hash { ... }
around the map
statement. That is required for keys
.
Note also that values %hash
can be any list of strings, such as one or more arrays, subroutine calls and whatnot.
Upvotes: 2
Reputation: 8386
Something like this may help you:
use List::MoreUtils qw{ uniq };
my %hash = ( a => 'Paul', b => 'Paul', c => 'Peter' );
my @uniq_names = uniq values %hash;
print "@uniq_names\n";
Keys are uniq always.
Upvotes: 2