0

Can anyone tell me where I am wrong? I can't figure it out.... Basically what my code is trying to do is to read the files and create a hash for each file, these hashes are organized into on hash. The user would input two parameters, one is the key of the outer hash, and the other is for the one inside. The ones I input are city and PIT; the same as the parameter I wrote before the line that breaks down....

I tried thousands of times, I keep getting this error: Can't use an undefined value as a HASH reference I have commented that line out in the code. The two files are cities.txt; school.txt. Their content are just as below: PIT\tPittsburgh NY\tNewYork

#!/bin/perl -w
use strict;
use Data::Dumper;
our %hash_all = ();
sub readHash{
    my @vars = @_;
    my $filename = $vars[0];
    my %iptable = ();
    if(open(IN,$filename.".txt")) {
            while(<IN>) {   
            my @tmp = split(/\t/);
            $iptable{$tmp[0]} = $tmp[1];
        }
    }
    return %iptable;
}

sub loadAll{
        my %school = readHash("school");
    my %city = readHash("cities");
    $hash_all{school} = \%school;
    $hash_all{city} = \%city;
    print Dumper(\%hash_all);
}

 sub queryValue{
    my @pars = @_;
    my $key1 = $pars[0];
    my $key2 = $pars[1];

    print "key1".$key1;
    print "key2".$key2;
    print Dumper(\%hash_all);   
    my %temp = %{$hash_all{"city"}};#THIS LINE WORKS
    print $temp{"PIT"}; #THIS LINE WORKS
    my %temp2 = %{$hash_all{$key1}};#THIS LINE HAS AN ERROR
    print $temp2{$key2};
}

loadAll();
my $par1 = <>;
my $par2 = <>;
queryValue($par1,$par2);
4

1 回答 1

4

您的问题可能是当您阅读$par1and时$par2,它们在末尾包含换行符。因此,您最终会寻找与 ."city\n"不同的哈希键"city"

确保chomp在输入参数上使用,例如chomp($par1). 那应该照顾它。

于 2013-02-01T10:35:55.770 回答