0

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 :)

4

3 に答える 3

3

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
于 2012-05-29T08:54:26.227 に答える
2

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.

于 2012-05-29T08:26:37.483 に答える
2

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.

于 2012-05-29T09:18:31.853 に答える