【问题标题】:Printing information from perl arrays/hashes从 perl 数组/哈希打印信息
【发布时间】:2013-07-31 05:04:11
【问题描述】:

我正在尝试访问从 api 返回的数据,我只是无法从数组中获取正确的值,我知道 API 正在返回数据,因为 Dumper 可以在屏幕上打印出来没问题。

当我尝试打印有关数组的所有信息时,我确切地知道要打印什么,我只是收到一个哈希。抱歉,如果这令人困惑,仍在学习中。

使用以下代码,我得到以下输出,

foreach my $hash (@{$res->data}) {
  foreach my $key (keys %{$hash}) {
    print $key, " -> ", $hash->{$key}, "\n";
  } 
}

输出

stat -> HASH(0xf6d7a0)
gen_info -> HASH(0xb66990)

你们有谁知道我可以如何修改上述内容以遍历 HASH 吗?

我要做的事情的底线是打印出数组的某个值。

请看我的数组转储器。

print Dumper(\$res->data);

http://pastebin.com/raw.php?i=1deJZX2f

我要打印的数据是 guid 字段。

我以为会是这样的

print $res->data->[1]->{guid}

但这似乎不起作用,我确定我只是在这里遗漏了一些东西,并且比我应该考虑的更多,如果有人可以指出我的写作方向或给我写正确的打印并解释什么我做错了,那太好了

谢谢

【问题讨论】:

  • 您要查找的字段是$res->data->{gen_info}{guid}

标签: arrays perl xml-rpc


【解决方案1】:

如果散列中有散列,你可以试试这个

foreach my $hash (@{$res->data}) {

    foreach my $key (keys %{$hash}) {

        my $innerhash = $hash->{$key};

        print $key . " -> " . $hash . "\n";

        foreach my $innerkey (keys %{$innerhash}) {

            print $key. " -> " . $innerhash->{$innerkey}. "\n";

        } 
    } 
 }

【讨论】:

  • 谢谢你,这正是我所需要的。我想要做的是确切地找出我需要在我的打印声明中放入的内容,就像在我的帖子底部一样。要仅打印 $res->data->... 中的 guid 字段,您知道我需要用什么替换...吗,数组不是我的强项。
【解决方案2】:

您拥有的结构是一个哈希数组。这在转储中显示为

# first hash with key being 'stat', 
#     Second hash as keys (traffic, mail_resps...) followed by values (=> 0)
'stat' => {
            'traffic' => '0', . 
            'mail_resps' => '0',

所以第一个散列中键的值是散列或散列的散列。

如果要打印出每个元素,则需要为第二个哈希的键添加一个额外的循环。

foreach my $hash (@{$res->data}) {  # For each item in the array/list
  foreach my $key (keys %{$hash}) {  # Get the keys for the first hash (stat,gen_info)
    foreach my $secondKey ( keys %{$hash->{$key}}) # Get the keys for the second hash
    {
      print $key, " -> ", $secondKey, " -> ",${$hash->{$key}}{$secondKey}, "\n";
    }
  } 
}

如果您只是对 guid 感兴趣,那么您可以通过以下方式访问它:

$res->data->[1]->{gen_info}{guid} 

其中 gen_info 是第一个哈希的键,而 guid 是第二个哈希的键

在使用 exits 访问之前,您可以检查密钥是否存在于第一个和第二个哈希中

$n = 1 # Index of the array you want to get the information 
if (( exists $res->data->[$n]->{gen_info} )  &&    # Check for the keys to exists in 
    ( exists $res->data->[$n]->{gen_info}{guid} )) # in each hash
{
   # do what you need to 
}
else
{
  print "ERROR: either gen_info or guid does not exist\n";
}

【讨论】:

  • 谢谢格伦,这正是我想要的,只需将数组的索引更改为 0 就可以了!有很多阅读要做然后我明白了。再次感谢您
  • [$n]后面的->可以省略。
  • 感谢您指出 [$n] 后面的 -> 可以省略。
猜你喜欢
  • 2012-07-22
  • 1970-01-01
  • 2016-02-21
  • 1970-01-01
  • 2015-01-09
  • 2020-10-16
  • 2013-06-24
  • 2011-10-27
  • 1970-01-01
相关资源
最近更新 更多