【问题标题】:How do I initialize values in a hash without a loop?如何在没有循环的情况下初始化哈希中的值?
【发布时间】:2011-04-03 03:11:13
【问题描述】:

我正在尝试找出一种无需通过循环即可初始化哈希的方法。我希望为此使用切片,但它似乎没有产生预期的结果。

考虑以下代码:

#!/usr/bin/perl
use Data::Dumper;

my %hash = ();
$hash{currency_symbol} = 'BRL';
$hash{currency_name} = 'Real';
print Dumper(%hash);

这确实按预期工作并产生以下输出:

$VAR1 = 'currency_symbol';
$VAR2 = 'BRL';
$VAR3 = 'currency_name';
$VAR4 = 'Real';

当我尝试如下使用切片时,它不起作用:

#!/usr/bin/perl
use Data::Dumper;

my %hash = ();
my @fields = ('currency_symbol', 'currency_name');
my @array = ('BRL','Real');
@hash{@array} = @fields x @array;

输出是:

$VAR1 = 'currency_symbol';
$VAR2 = '22';
$VAR3 = 'currency_name';
$VAR4 = undef;

显然有问题。

所以我的问题是:给定两个数组(键和值)初始化散列的最优雅的方法是什么?

【问题讨论】:

    标签: arrays perl hash slice


    【解决方案1】:
    use strict;
    use warnings;  # Must-haves
    
    # ... Initialize your arrays
    
    my @fields = ('currency_symbol', 'currency_name');
    my @array = ('BRL','Real');
    
    # ... Assign to your hash
    
    my %hash;
    @hash{@fields} = @array;
    

    【讨论】:

      【解决方案2】:

      因此,您想要的是使用一个数组作为键填充散列,并使用一个数组作为值。然后执行以下操作:

      #!/usr/bin/perl
      use strict;
      use warnings;
      
      use Data::Dumper; 
      
      my %hash; 
      
      my @keys   = ("a","b"); 
      my @values = ("1","2");
      
      @hash{@keys} = @values;
      
      print Dumper(\%hash);'
      

      给予:

      $VAR1 = {
                'a' => '1',
                'b' => '2'
              };
      

      【讨论】:

      • 谢谢——这正是我想要的。这几乎太简单了。
      【解决方案3】:
          %hash = ('current_symbol' => 'BLR', 'currency_name' => 'Real'); 
      

      my %hash = ();
      my @fields = ('currency_symbol', 'currency_name');
      my @array = ('BRL','Real');
      @hash{@fields} = @array x @fields;
      

      【讨论】:

      • 感谢您提供有关如何初始化哈希的教科书示例。然而,这不是我要找的。我想看看是否可以用拼接来完成。
      • 但是对于第一个谷歌结果,这是一个非常有用的复习/语法确认
      【解决方案4】:

      第一个,试试

      my %hash = 
      ( "currency_symbol" => "BRL",
        "currency_name" => "Real"
      );
      print Dumper(\%hash);
      

      结果将是:

      $VAR1 = {
                'currency_symbol' => 'BRL',
                'currency_name' => 'Real'
              };
      

      【讨论】:

      • 感谢您提供有关如何初始化哈希的教科书示例。然而,这不是我要找的。我想看看是否可以用拼接来完成。
      • 实际上@emx,我更关心向您展示为什么您的 Data:Dumper 输出看起来不像散列。
      • 我认为你的本意是拒绝我而不是接受我,但我认为我也不值得。
      • 对。实际上,这确实一直困扰着我-谢谢您的澄清:)
      • @emx,到目前为止你做得很好。很抱歉没有理解您的问题的要点。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2014-08-22
      相关资源
      最近更新 更多