1

我正在尝试生成散列的散列。我正在从 txt 文件中读取输入并将数据转换为哈希值。txt文件的格式是

flintstones : lead=fred pal=barney
jetsons : lead=george wife=jane "his boy"=elroy
simpsons : lead=homer wife=marge kid=bart

哈希格式的哈希为

%HoH = (
    flintstones => {
    lead      => "fred",
    pal       => "barney",
    },
    jetsons     => {
    lead      => "george",
    wife      => "jane",
    "his boy" => "elroy",
    },
    simpsons    => {
    lead      => "homer",
    wife      => "marge",
    kid       => "bart",
},
 );

我正在写的代码是

use strict;
use warnings;

my %hash = ();
my $hash1 = {};
open (FH, "2.txt") or die "file not found";
while (<FH>) {
my @array = split (":", $_);
$array[0] =~ s/^\s*//;
$array[0] =~ s/\s*$//;
$array[1] =~ s/^\s*//;
$array[1] =~ s/\s*$//;
my @array1 = split (" ", $array[1]);
for (0..$#array1) {
    my ($key, $value) = split ("=", $array1[$_]);
    $hash{$array[0]}{$key} = $value;
    #$hash1->{$key} = $value;
    #print "    $hash1{$key} \n";
}
#$hash{$array[0]} = $%hash1;

}
close FH;
print " value is %hash" ;

没有得到输出。我的代码有什么问题

4

1 回答 1

1
use strict;
use warnings;

# match chars or chars inside '"' following by '=' and chars for hash value
my $re = qr/(?: (\w+) | "(.+?)" ) = (\w+)/x;
my %hash;

open (FH, "<", "2.txt") or die $!;
while (<FH>) {
  my ($k, $s) = split /\s*:\s*/, $_, 2;
  my %hash1 = grep defined, $s =~ /$re/g;
  $hash{$k} = \%hash1;
}
close FH;

use Data::Dumper;
print "value is ", Dumper \%hash;
于 2013-08-13T13:30:00.430 回答