2013-03-06 110 views
1

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

代码示例:

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 

如果发现用户的代码返回的密码。我怎样才能返回用户名?

+1

您正在使用'$ pass'和'$ passw',其中一个可能是输入错误。 – 2013-03-06 20:28:57

+0

安全无关紧要,只学习! – Raid5 2013-03-06 20:30:15

+0

对不起,输入错误。 Thnaks :) – Raid5 2013-03-06 20:32:24

回答

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;将返回用户名。我无法想象这就是你想要的。另一方面,找到与给定密码相对应的用户听起来也不太可能。

+0

而且你的论点是100%正确的。我的错误 - 道歉,其工作再次感谢 – Raid5 2013-03-06 20:44:14

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; 
} 
+0

我读取移位$ pass作为传递给子例程的密码。否则,OP的问题是,我如何获得散列键? – doncoyote 2013-03-06 20:52:01