我试图通过读取文件在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_arrn";
$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?????
因为每个值都引用了同一个数组
试试这样写:
#!/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'
};
@temp_arr
是对全局变量@temp_arr
的引用。你反复地重新初始化它,但它仍然是对原始变量的引用。
您需要在词法上限定@temp_arr
(my @temp_arr=($2,$3,$4);
)的作用域,或者传递一个新的引用到散列($HASH{$1} = [ $2,$3,$4 ];
)
试试这个:
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;
试试这个
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);
除了"open"语句中的错误,尽量保持简单,然后使其不可读。
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: $bn";
$HASH{$a}="$b";
print "Hash now ..n";
foreach $k (sort keys %HASH){
print "Key: $k -- HASH{$k} = $HASH{$k}n";
}
}