从Perl中的多维哈希中抓取列表 [英] Grabbing a list from a multi-dimensional hash in Perl

查看:270
本文介绍了从Perl中的多维哈希中抓取列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编程Perl(本书)中,我读到可以创建一个字典,其中的条目包含一个数组,如下所示:

  $ wife {Jacob} = [Leah,Rachel,Bilhah,Zilpah]; 

假设我想抓取 $ wife {Jacob } 列表中。



如果我尝试:

  $ key =雅各布; 
表示$ wife {$ key};

我得到:

  ARRAY(0x56d5df8)

这让我相信我得到了一个参考,而不是实际的列表。

解决方案

b

  • perllol

  • perldsc

  • perlreftut



  • 有关使用复杂数据结构和参考的信息。

    基本上,散列只能有标量作为值,但引用是标量,因此,您需要在散列内保存一个arrayref,并且必须将它解引用到一个数组中。



    要取消引用,请使用 @ {...} 语法。

      say @ {$ wife {Jacob}}; 

     说@ {$ wife {Jacob}}; #打印空间在


    之间的元素

    In Programming Perl (the book) I read that I can create a dictionary where the entries hold an array as follows:

    $wife{"Jacob"} = ["Leah", "Rachel", "Bilhah", "Zilpah"];
    

    Say that I want to grab the contents of $wife{"Jacob"} in a list. How can I do that?

    If I try:

    $key = "Jacob";
    say $wife{$key};
    

    I get:

    ARRAY (0x56d5df8)
    

    which makes me believe that I am getting a reference, and not the actual list.

    解决方案

    See

    for information on using complex data structures and references.

    Essentially, a hash can only have scalars as values, but references are scalars, Therefore, you are saving an arrayref inside the hash, and have to dereference it to an array.

    To dereference a reference, use the @{...} syntax.

    say @{$wife{Jacob}};
    

    or

    say "@{$wife{Jacob}}"; # print elements with spaces in between
    

    这篇关于从Perl中的多维哈希中抓取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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