perl学习笔记15_把hasharray存储在文件中
目录
可以把hash或array存储在文件中, 再从文件中把变量load回来
#加载模块
use Storable qw/store retrieve/;
#定义变量
my %data0 = ("a", "aaa", "b", "bbb", "c", "ccc", "d", "ddd"); #一个一维hash
my %data1 = (); #一个二维hash
$data1{"1"} = \%data0; # value是对%data0的引用
%{$data1{"2"}} = %data0; # value是对%data0的copy+引用
my @data2 = (1, 2, 3, \%data0, \%data0); # 一个array+hash混合结构
#把变量存入文件
store(\%data0, "data0.store");
store(\%data1, "data1.store");
store(\@data2, "data2.store");
#从文件中把变量恢复回来
my %data0_r = %{retrieve('data0.store')};
my %data1_r = %{retrieve('data1.store')};
my @data2_r = @{retrieve('data2.store')};
#打印下恢复来的变量:
print "data0:\n";
foreach my $k (keys %data0_r) {
print "$k => $data0_r{$k}\n";
}
print "\n";
print "data1:\n";
foreach my $k0 (keys %data1_r) {
print "$k0\n";
foreach my $k1 (keys %{$data1_r{$k0}}) {
print " $k1 => $data1_r{$k0}{$k1}\n";
}
}
print "\n";
print "data2:\n";
foreach my $ele (@data2_r) {
if (ref($ele) eq "") { # 标量
print "$ele\n";
} elsif (ref($ele) eq "HASH") { # hash
print "HASH\n";
foreach my $k (keys %{$ele}) {
print " $k => ${$ele}{$k}\n";
}
}
}
print "\n";
输出内容:
data0:
b => bbb
d => ddd
a => aaa
c => ccc
data1:
2
d => ddd
b => bbb
c => ccc
a => aaa
1
d => ddd
b => bbb
c => ccc
a => aaa
data2:
1
2
3
HASH
c => ccc
a => aaa
b => bbb
d => ddd
HASH
c => ccc
a => aaa
b => bbb
d => ddd