https://www.cnblogs.com/yeungchie/
便于数据结构的存储和还原
这里的方法是将HASH
转为字符串
写入文件的,再读取文件中字符串内容转为HASH
使用JSON
作为数据交换格式 ( JavaScript Object Notation )
使用 JSON 模块
use JSON;
HASH 转 JSON
- hashToJson.pl
# 省略一堆次要的模块声明
use JSON;
my %hash_data = (
server => "eda",
release => "6.10",
memTotal => "15G",
memRatio => "0.144396",
cores => "6",
cpuRatio => "0.0145719489981785",
time => "1624202821",
load => "0.29/0.07/0.02",
);
say Dumper \%hash_data;
my $json = new JSON; # 创建 JSON 对象
my $json_data = $json->pretty->encode(\%hash_data); # 编码成 JSON 格式
say Dumper $json_data;
# JSON 写入
my $file = IO::File->new('>hashToJson.txt');
printf $file $json_data;
$file->close;
hash_data
$VAR1 = {
'memRatio' => '0.144396',
'memTotal' => '15G',
'cores' => '6',
'cpuRatio' => '0.0145719489981785',
'time' => '1624202821',
'server' => 'eda',
'release' => '6.10',
'load' => '0.29/0.07/0.02'
};json_data
$VAR1 = '{
"memRatio" : "0.144396",
"memTotal" : "15G",
"cores" : "6",
"cpuRatio" : "0.0145719489981785",
"time" : "1624202821",
"server" : "eda",
"release" : "6.10",
"load" : "0.29/0.07/0.02"
}
';
JSON 转 HASH
jsonToHash.pl
# 省略一堆次要的模块声明
use JSON;
# JSON 读取
my $file = new IO::File '<hashToJson.txt';
my @file_data = <$file>;
$file->close;
my $json_data = join '',@file_data;
say Dumper $json_data;
# 解码
my $hash_data = decode_json $json_data;
say Dumper $hash_data;
# Tips : 解引用 %{$hash_data}
json_data
$VAR1 = '{
"memRatio" : "0.144396",
"memTotal" : "15G",
"cores" : "6",
"cpuRatio" : "0.0145719489981785",
"time" : "1624202821",
"server" : "eda",
"release" : "6.10",
"load" : "0.29/0.07/0.02"
}
';hash_data
$VAR1 = {
'time' => '1624202821',
'release' => '6.10',
'server' => 'eda',
'memRatio' => '0.144396',
'memTotal' => '15G',
'load' => '0.29/0.07/0.02',
'cpuRatio' => '0.0145719489981785',
'cores' => '6'
};