【问题标题】:Hashes array elements copy哈希数组元素复制
【发布时间】:2012-01-02 10:35:34
【问题描述】:

我的哈希数组:

@cur = [
          {
            'A' => '9872',
            'B' => '1111'
          },
          {
            'A' => '9871',
            'B' => '1111'
          }
        ];

预期结果:

@curnew = ('9872', '9871');

任何仅获取第一个哈希元素值的简单方法
这并将其分配给一个数组?

【问题讨论】:

    标签: arrays perl copy elements


    【解决方案1】:

    请注意哈希是无序的,所以我将 first 这个词的意思是 按字典顺序排列

    map {                               # iterate over the list of hashrefs
        $_->{                           # access the value of the hashref
            (sort keys $_)[0]           # … whose key is the first one when sorted
        }
    }
    @{                                  # deref the arrayref into a list of hashrefs
        $cur[0]                         # first/only arrayref (???)
    }
    

    表达式返回qw(9872 9871)

    @cur = […] 那样将arrayref 分配给数组可能是一个错误,但我从表面上看。


    奖金perl5i解决方案:

    use perl5i::2;
    $cur[0]->map(sub {
        $_->{ $_->keys->sort->at(0) } 
    })->flatten;
    

    表达式返回与上面相同的值。这段代码有点长,但 IMO 更具可读性,因为执行流程严格从上到下,从左到右。

    【讨论】:

      【解决方案2】:

      首先你的数组必须定义为

      my @cur = (
          {
              'A' => '9872',
              'B' => '1111'
          },
          {
              'A' => '9871',
              'B' => '1111'
          }
      );
      

      注意括号

      #!/usr/bin/perl 
      use strict;
      use warnings;
      use Data::Dump qw(dump);
      
      my @cur = (
          {
              'A' => '9872',
              'B' => '1111'
          },
          {
              'A' => '9871',
              'B' => '1111'
          }
      );
      my @new;
      foreach(@cur){
          push @new, $_->{A};
      }
      dump @new;
      

      【讨论】:

        【解决方案3】:
        use Data::Dumper;
        my @hashes = map (@{$_}, map ($_, $cur[0]));
        my @result = map ($_->{'A'} , @hashes);    
        print Dumper \@result;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-26
          • 2011-12-14
          • 1970-01-01
          • 2021-08-01
          • 2012-07-24
          • 2011-12-13
          相关资源
          最近更新 更多