5

Perl 调试打印 HASH 内容

 2 years ago
source link: https://blog.frytea.com/archives/608/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Perl 调试打印 HASH 内容

December 23, 2021 • Read: 8 • 技术价值

本文首发于: https://blog.frytea.com/archives/608/

在调试 Perl 程序时常常需要打印哈希表内容,虽然可以直接使用 foreach 打印,但数据复杂了就难办了,此时可以将 Hash 表转换为 json 文本再打印:

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;

如果没有 json 包需要安装一下:

cpan -i JSON

如果下载太慢,可以使用 tuna 提供的 cpan 国内镜像源:

# 若tuna cpan不在镜像列表中则将其加入列表首位
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()'

测试一下,效果还可以:

$ 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"

---------------------
Author: Frytea
Title: Perl 调试打印 HASH 内容
Link: https://blog.frytea.com/archives/608/
Copyright: This work by TL-Song is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK