无法在perl中读取哈希值



在perl代码中,我试图通过使用键&存储在2个独立数组中的值。为了初始化数组,从文本文件中读取数据;然后进行处理。

我遵循以下语法来存储密钥&值转换为散列:

@hash{@key}=@values

当我尝试显示哈希的内容时,我能够单独显示key的内容&而不是数值。为什么散列没有任何值?如何解决这一问题

文本文件

NAME,OWE,RECEIVE
RAM,2000,1000
TEJA,1500,2200
NANDHINI,400,3000
RAGHAV,0,5000
ETHI,100,2500
KESHAV,400,400

以下是我的代码:

$i = 0;
open(FH, "<expenses_details.txt") or die "Couldn't open the file";
%nameo;
while ($line = <FH>)
{
    chomp($line);
    if ($i == 0)
    {
        $i++;
        next;
    }
    ($name, $owe, $receive) = split(',', $line);
    #print "Name is:$name, Owe:$owe, Receive:$receive n"; 
    push(@names, $name); # Creating name array
    push(@owes, $owe);  #creating owe array
    push(@receives, $receive); #creating receive array
}
close FH;
print "Name array:n";
foreach (@names)
{
    print "$_n";
}
print "nOWE array:n";
foreach (@owes)
{
    print "$_n";
}
#Initialising owe hash
@nameo{@names} = @owes;
$size = keys %nameo;
print "nsize is $sizen";
foreach my $key (keys %nameo)
{
    print $key;
    print $nameo[$key];
    print "n";
}

获得的输出:

Name array:
RAM
TEJA
NANDHINI
RAGHAV
ETHI
KESHAV
OWE array:
2000
1500
400
0
100
400
size is 6
TEJA
RAM
KESHAV
ETHI
NANDHINI
RAGHAV
Perl不是PHP(也不是Ruby(。要访问散列值,请使用大括号,而不是方括号:
print $nameo{$key};

你应该使用严格的和警告。Strict会告诉您尝试访问未声明的@nameo

最新更新