微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将HASH 存入文件 然后将文件转为hash

perl Hash 我比较喜欢的,好多数据我都是存在 hash中。

但是有些数据我是不想他,程序退出后不保存的。所以想把数据存入文件中。

这个东西研究了 好多个小时,想找一个和 SHELL 语言一样的 >> << 文件读写方式。

 

经过 google 很一下。发现有几个方案是比较好的。

 

方案一Dump :

#!/bin/perl -w
use strict;
use Data::Dump 'dump';
use FileHandle;
my $file = "data.out";

{
 my %hash = ("apples"=>17,
    "bananas"=>9,
    "oranges"=>"none");
 my $str = Data::Dumper->Dump([ /%hash ],[ '$hashref' ]);
 my $out = new FileHandle ">$file";
 print $out $str;
 close $out;
}

{
 my $in = new FileHandle "<$file";
 local($/) = "";
 my $str  = <$in>;
 close $in;
 #print "Input: $str";
 my($hashref);
 eval $str;
 my %hash = %$hashref;
 print dump(/%hash),"/n";
}

 

 

方案2:使用Storable

 

#!/usr/bin/perl -w
use strict;
use Data::Dumper;
use Storable;
my %test = (this => ['that','the','other','323232'],
   that => ['this','121122']
   );
warn Dumper(/%test);
# Save the hash to a file:
store /%test,'file.txt';
# Retrieve the hash from the file.
my $testref1 = retrieve('file.txt');
warn Dumper($testref1);

 

方案3:XML ()

没有细细研究

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐