检索动态哈希的密钥

时间:2013-03-06 20:23:46

标签: perl

如何从动态哈希中检索“密钥”?

代码示例:

sub HASH($){
    my %hash;
    my $pass = shift;
    open (my $file, '<', "infofile") || die "No such file or dir\n";
    %hash=map split, <$file>;
    return $hash{$pass};
}

我的infofile看起来像这样:

user   passwd
raid   12345

如果找到用户,代码将返回密码。我怎样才能返回用户名?

2 个答案:

答案 0 :(得分:0)

如果添加(用于调试目的)哈希的打印,

open (my $file, '<', "infofile") || die "No such file or dir\n";
%hash=map split, <$file>;

for (keys %hash) {
  print "$_: $hash{$_}\n";
}
你会看到:

raid: 12345
user: passwd

因此我认为,您的变量$pass实际上是用户名,return $pass;会返回用户名。我无法想象这就是你想要的。另一方面,找到与给定密码相对应的用户也不太可能。

答案 1 :(得分:0)

sub HASH($){
 my %hash;
 my $pass = shift;
 open (my $file, '<', "infofile") || die "No such file or dir\n";
 %hash=map split, <$file>;
 my ($user,$selecteduser);
  foreach $user (keys %hash){
   $selecteduser = $user if $hash{$user} eq $pass;
  }
 return $selecteduser;
}
相关问题