当你需要在一个序列中查找一个唯一的元素值,你可以考虑使用哈希表来查找。
例如,当你有一些电子邮件的地址序列,你需要给列表中的每一个人都发一封电子邮件。但是,如果这些列表中有重复的地址,而你又不想给同一个地址发送两封邮件。
在这种情况下,你可以使用下面的代码来处理这个邮件列表并只决定那些唯一的元素:
@admin = qw(bob joefred bill tim);
@operators = qw(bob fredtimtravis
@powerusers = qw(fred bill jane sally roger);
@users = qw(tom john ralph
print "Original users: @{[sort(@admin, @operators, @powerusers, @users)]} ";
%before = ();
@unique = sort grep{ ! $before++ } @admin, @operators, @powerusers, @users;
print "Unique users: @unique ";
这个程序的输出结果如下:
Original users: alex bill bill bob bobfredfredfredjanejoe
john kelly
Unique users: alex bill bob fredjanejoe john kelly
tim tom travis
如果你需要处理每一个元素,你可以检查并处理循环中的元素,就像下面程序所描述的一样(和前面程序使用同样的用户列表):
print "Unique users: ";
%before = ();
for $user (@admin, @operators, @powerusers, @users)
{
next if ($before++);
# do whatever processing here
}
这样,使用哈希表是一个查询列表中唯一元素的简便方法。