1. Hash of hash
#!/usr/bin/perl -w use strict; use Data::Dumper; my $hash_ref = {}; my ($who, $field, $key, $value); while (<DATA>) { next unless s/^(.*?):\s*//; $who = $1; for $field ( split ) { ($key, $value) = split /=/, $field; $hash_ref->{$who}->{$key} = $value; } } print Dumper ($hash_ref); for my $family (keys %{$hash_ref}) { print "$family: "; for my $role (keys %{$hash_ref->{$family}}) { print "$role=$hash_ref->{$family}->{$role} "; } print "\n"; }
Output:
$VAR1 = { 'xiongxiong' => { 'pet' => 'garfield', 'husbnad' => 'tom', 'wife' => 'pretty', 'pal' => 'jerry' }, 'flintstones' => { 'pet' => 'dino', 'wife' => 'wilma', 'husband' => 'fred', 'pal' => 'barney' } }; xiongxiong: pet=garfield husbnad=tom wife=pretty pal=jerry flintstones: pet=dino wife=wilma husband=fred pal=barney
2. Hash of hash
#!/usr/bin/perl -w use strict; my %HoH; while (<DATA>) { next unless s/^(.*?):\s*//; my $who = $1; for my $field (split) { my ($key, $value) = split /=/, $field; $HoH{$who}{$key} = $value; } } for my $family (keys %HoH) { print "$family: "; for my $role (keys %{$HoH{$family}}) { print "$role=$HoH{$family}{$role} "; } print "\n"; } __DATA__ flintstones: husband=fred pal=barney wife=wilma pet=dino xiongxiong: husbnad=tom pal=jerry wife=pretty pet=garfield
没有评论:
发表评论