2025年3月21日 星期五 甲辰(龙)年 月廿 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Perl

Perl 调试打印 HASH 内容

时间:10-29来源:作者:点击数:55

在调试 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不在镜像列表中则将其加入列表首位
  • 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

测试一下,效果还可以:

  • $ 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"
  • }
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门