如何在Perl中打印哈希结构? [英] How do I print a hash structure in Perl?

查看:998
本文介绍了如何在Perl中打印哈希结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例子:

 %hash =(2010 => 21,2009 => 9); 

$ hash = {
a => {
0 => {test => 1},
1 => {test => 2},
2 => {test => 3},
3 => {test => 4},
},
};

如何打印散列?

解决方案

是否要打印整个散列或特定键值对?你期望的结果是什么?如果仅仅是为了调试目的,你可以这样做:

  use Data :: Dumper; 
打印Dumper%hash; #或\%哈希将其封装为单个哈希引用实体;

如果您使用每个函数($($ key,$ value)= each%hash){$ b $ {

  b打印$ key = $ value\\\
;

或者 / code> foreach 构造如果您想对其进行排序:

  for my $键(排序键%hash){
print$ key = $ hash {$ key} \\\
;

$ / code>

或者,如果您只想要某些值,可以使用散列片段,例如:

  print@hash {qw {2009 2010}} \; 

等等,总有不止一种方法可以做到,尽管它有助于了解什么你首先要做的是煎炸:)

Examples:

%hash = (2010 => 21, 2009=> 9);

$hash = {
    a => {
        0 => {test => 1},
        1 => {test => 2},
        2 => {test => 3},
        3 => {test => 4},
    },
};

How do I print the hash?

解决方案

Do you want to print the entire hash, or specific key, value pairs? And what is your desired result? IF it's just for debugging purposes, you can do something like:

use Data::Dumper;
print Dumper %hash; # or \%hash to encapsulate it as a single hashref entity;

You can use the each function if you don't care about ordering:

while ( my($key, $value) = each %hash ) {
    print "$key = $value\n";
}

Or the for / foreach construct if you want to sort it:

for my $key ( sort keys %hash ) {
    print "$key = $hash{$key}\n";
}

Or if you want only certain values, you can use a hash slice, e.g.:

print "@hash{qw{2009 2010}}\n";

etc, etc. There is always more than one way to do it, though it helps to know what you're frying to do first :)

这篇关于如何在Perl中打印哈希结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆