【问题标题】:Perl: change element/s in array of hashesPerl:更改哈希数组中的元素
【发布时间】:2016-05-19 19:04:57
【问题描述】:

如何在 Perl 中更改哈希数组中的元素?

假设我有以下数组并想更改商品的价格:

my @clothes = (
    { item => 'Jeans',  colour => 'Blue',  price => 50 },
    { item => 'Shawl',  colour => 'Red',   price => 30 },
    { item => 'Blazer', colour => 'Brown', price => 100 },
    { item => 'Suit',   colour => 'Black', price => 40 },
    { item => 'Top',    colour => 'White', price => 25 }
);

【问题讨论】:

    标签: arrays perl


    【解决方案1】:

    您所拥有的称为哈希数组。更准确地说,你所拥有的是一组对哈希的引用。这意味着

    $clothes[3]
    

    是对哈希的引用,所以

    $clothes[3]->{price}
    

    是该哈希的price 元素的值。索引之间可以省略->,所以下面是等价的:

    $clothes[3]{price}
    

    这意味着你想要

    $clothes[3]{price} = 45;
    

    如果你不知道你想要的元素的索引,你可以扫描数组。请记住,数组的每个元素都是对其中一个哈希值的引用。

    for my $clothes_item (@clothes) {
        if ($clothes_item->{item} eq 'Suit') {
           $clothes_item->{price} = 45;
        }
    }
    

    【讨论】:

      【解决方案2】:

      你没有二维数组——你有一个 hashrefs 数组。如果您想更改特定商品的价格,您需要知道保存它所属的哈希引用的数组索引。

      $clothes[1]->{price} = 42;
      

      有关您可以对哈希数组执行的其他操作,请参阅 perldsc 的恰当命名的 Arrays of Hashes 部分。

      【讨论】:

      • 正是我想要的
      【解决方案3】:
      #!/usr/bin/perl
      
      use strict;
      use warnings;
      use Data::Dumper;
      
      my @clothes = 
          (
              {item => 'Jeans', colour => 'Blue', price => 50},
              {item => 'Shawl', colour => 'Red', price => 30},
              {item => 'Blazer', colour => 'Brown', price => 100},
              {item => 'Suit', colour => 'Black', price => 40},
              {item => 'Top', colour => 'White', price => 25}    
          );
      
      for my $next_item ( @clothes ){
              $next_item->{price} = 0.99
      }
      
      print Dumper( \@clothes );
      

      【讨论】:

      • @MattJacob 所有商品 99 美分,一切都必须走!
      • @ThisSuitIsBlackNot 哈哈哈
      猜你喜欢
      • 2013-11-01
      • 1970-01-01
      • 2021-08-01
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 2019-07-30
      • 2012-04-28
      相关资源
      最近更新 更多