用户定义的散列搜索

User defined search of a hash

Perl 新手。使用 Windows 10 w/ Padre IDE。我有一个问题一直困扰着我,它可能很简单,但我还没有在网上找到答案。

这是我搜索之前一直在运行的代码。它读取一个 list.txt 文件,其中包含名称和匹配的 phone 数字,所以我有两个哈希值(一个是名称 => 数字,第二个是数字 =>)。

my $search = "";

print "File name to be read in: ";
my $textFile = <>;

open FILE, $textFile;
my %hash;

while (<FILE>)
{
    chomp;
    my ($key, $val) = split / /;

    $hash{$key} .= exists $hash{$key} ? "$val" : $val;
}

close FILE;

open FILE, $textFile;
my %hash2;

while (<FILE>)
{
    chomp;
    my ($val, $key) = split / /;

    $hash2{$key} .= exists $hash2{$key} ? "$val" : $val;
}

close FILE;


print "(N) for name (#) for number search and (.) to exit: ";

$search = <>;

if ($search == "N")                #heres where we have the problem
{
        print "Enter name: ";  
        my $person = <>;           #user defined search looks for Bob Smith
        print $hash{$person};      #prints nothing
}

但是,当我将搜索设置为非用户定义时,它会完美地工作,如下所示:

if ($search == "N")                
{
        #print "Enter name: ";  
        #my $person = <>;           
        print $hash{"Bob Smith"};      #prints Bob Smith's number
}

作为记录,我将 $search 打印到屏幕以验证我首先输入名称时没有问题。当我用户定义搜索时,哈希值不会拉高。当名称被专门编码到哈希函数中时,它每次都有效。

感谢您帮助遇到困难的 Perl 菜鸟。

你有一个尾随换行符。比较前需要chomp:

$search = <>;
chomp $search;

此外,您应该使用字符串比较 eq:

if ($search eq "N")