zoukankan      html  css  js  c++  java
  • [ Perl ] HASH 读写

    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'
    };

  • 相关阅读:
    新博客安家
    Win32设置与获取cookies的几种方法
    Win32 操作剪切板
    搜索PEB结构获取Kernel32.dll基址
    动人心魄音乐 [身骑白马 徐佳莹]
    单例模式与静态方法的区别(转载)
    个人回顾
    关于引入每日站会的思考
    2017年的总结和回顾
    《知易行难》回顾
  • 原文地址:https://www.cnblogs.com/yeungchie/p/14933003.html
Copyright © 2011-2022 走看看