简体   繁体   English

如何在Perl中的哈希中获取所有不同的值(或键)

[英]How to get all different values(or keys) in a hash in Perl

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,John,John,Bob,Bob,Paul的哈希-是否有可以返回的函数:

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 :) 我希望你能理解我的问题,谢谢:)

TIMTOWTDI: TIMTOWTDI:

my @unique = keys { reverse %hash };

Note the performance caveat with reverse though: 注意与性能警告reverse ,虽然:


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. 同样,这必须解散一个哈希并构建一个全新的哈希,这可能需要花费一些时间来处理大型哈希,例如来自DBM文件的哈希。

 %by_name = reverse %by_address; # Invert the hash 

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. 键始终是uniq。

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. 注意使用花括号在map语句周围形成匿名哈希{ ... } That is required for keys . 这是keys所必需的。

Note also that values %hash can be any list of strings, such as one or more arrays, subroutine calls and whatnot. 还请注意, values %hash可以是字符串的任何列表,例如一个或多个数组,子例程调用等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM