在调试 Perl 程序时常常需要打印哈希表内容,虽然可以直接使用 foreach 打印,但数据复杂了就难办了,此时可以将 Hash 表转换为 json 文本再打印: use JSON; my $data = {‘info’=> “test”, ‘struct’ => {‘test1’=>’test1’, ‘test2’=>’test2’}};
在调试 Perl 程序时常常需要打印哈希表内容,虽然可以直接使用 foreach
打印,但数据复杂了就难办了,此时可以将 Hash 表转换为 json 文本再打印:
1 2 3 4 5 6 7
| use JSON;
my $data = {'info'=> "test", 'struct' => {'test1'=>'test1', 'test2'=>'test2'}}; my $json = new JSON;
my $json_text = $json->pretty->encode ($data); print $json_text;
|
如果没有 json 包需要安装一下:
如果下载太慢,可以使用 tuna 提供的 cpan 国内镜像源:
1 2 3 4 5 6 7 8 9 10
| if ! ( perl -MCPAN -e 'CPAN::HandleConfig->load();' \ -e 'CPAN::HandleConfig->prettyprint("urllist")' | grep -qF 'https://mirrors.tuna.tsinghua.edu.cn/CPAN/' ); then perl -MCPAN -e 'CPAN::HandleConfig->load();' \ -e 'CPAN::HandleConfig->edit("urllist", "unshift", "https://mirrors.tuna.tsinghua.edu.cn/CPAN/");' \ -e 'CPAN::HandleConfig->commit()' fi
|
测试一下,效果还可以:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| $ perl -e 'use JSON; > > my $data = {'info'=> "test", 'struct' => {'test1'=>'test1', 'test2'=>'test2'}}; > my $json = new JSON; > #$json->sort_by(sub { ncmp($JSON::PP::a, $JSON::PP::b) }); > my $json_text = $json->pretty->encode ($data); > print $json_text;' { "struct" : { "test2" : "test2", "test1" : "test1" }, "info" : "test" }
|
参考文献