在创建哈希散列时没有得到输出

时间:2013-08-13 12:18:55

标签: perl

我正在尝试生成散列哈希值。我正在读取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" ;

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

1 个答案:

答案 0 :(得分: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;