在perl中从文件读取时,hash不能正确打印

时间:2014-07-25 16:17:21

标签: perl

我正在尝试通过读取文件在perl中构建哈希。 文件内容如下:

s1=i1
s2=i2
s3=i3

我的代码如下:

my $FD;
open ($FD, "read") || die "Cant open the file: $!";
while(<$FD>){
    chomp $_;
    print "\n Line read = $_\n";
    $_ =~ /([0-9a-z]*)=([0-9a-zA-Z]*)/;
    @temp_arr=($2,$3,$4);
    print "Array = @temp_arr\n";
    $HASH{$1}=\@temp_arr;
    print "Hash now = ";
    foreach(keys %HASH){print "$_ = $HASH{$_}->[0]\n";};


}

我的输出如下

 Line read = s1=i1
Array = i1
Hash now = s1 = i1

 Line read = s2=i2
Array = i2
Hash now = s2 = i2
s1 = i2

 Line read = s3=i3
Array = i3
Hash now = s2 = i3
s1 = i3
s3 = i3

为什么最后所有键的值都打印为i3 ?????

5 个答案:

答案 0 :(得分:3)

因为您要在每个值中引用相同的数组。

尝试这样的事情:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my %result;

open my $fh, '<', 'read' or die $!;
while (my $line=<$fh>) {
    chomp $line;
    my ($key, $value)=split /=/, $line, 2;
    die "$key already exists" if (exists $result{$key});
    $result{$key}=$value;
}

print Dumper(\%result);

输出是:

$VAR1 = {
          's1' => 'i1',
          's3' => 'i3',
          's2' => 'i2'
        };

答案 1 :(得分:2)

\@temp_arr是对全局变量@temp_arr的引用。您正在重复初始化它,但它仍然是对原始变量的引用。

您需要词法范围@temp_arrmy @temp_arr=($2,$3,$4);)或将新引用传递给哈希($HASH{$1} = [ $2,$3,$4 ];

答案 2 :(得分:1)

试试这个:

my $FD;
open ($FD, "read") || die "Cant open the file: $!";
for(<$FD>){
   chomp $_;
   push(@temp_arr,$1,$2) if($_=~/(.*?)=(.*)/);
}
%HASH=@temp_arr;
print Dumper \%HASH;

答案 3 :(得分:0)

试试这个。

open (my $FD, "read") || die "Cant open the file: $!";
my %HASH = map {chomp $_; my @x = split /=/, $_; $x[0] => $x[1]} <$FD>;
print "Key: $_ Value: $HASH{$_}\n" for (sort keys %HASH);

答案 4 :(得分:-1)

除了你的&#34;打开&#34;中的错误声明,尽量保持简单,然后让它变得不可读。

my ($FD, $a, $b, $k);
$FD = "D:\\Perl\\test.txt";
open (FD, "<$FD") or die "Cant open the file $FD: $!";
while(<FD>){
    chomp $_;
    print "\n Line read = $_\n";
    ($a, $b) = split('=', $_);
    print "A: $a, B: $b\n";
    $HASH{$a}="$b";
    print "Hash now ..\n";
    foreach $k (sort keys %HASH){
        print "Key: $k -- HASH{$k} = $HASH{$k}\n";
    }
}