【问题标题】:Is it possible to push a key-value pair directly to hash in perl?是否可以将键值对直接推送到 perl 中的散列?
【发布时间】:2020-11-25 00:09:55
【问题描述】:

我知道pushing 只能传递给数组,而不是哈希。但是允许将键值对直接推送到散列会更方便(我仍然很惊讶在 perl 中这是不可能的)。我有一个例子:

#!/usr/bin/perl -w

#superior words begin first, example of that word follow
my @ar = qw[Animals,dog Money,pound Jobs,doctor Food];
my %hash;
my $bool = 1;

sub marine{
    my $ar = shift if $bool;
    for(@$ar){
        my @ar2 = split /,/, $_;
        push %hash, ($ar2[0] => $ar2[1]);
    }
}

marine(\@ar);
print "$_\n" for keys %hash;

这里我有一个数组,它有两个单词,分别用, 逗号分隔。我想从中做一个散列,使第一个成为键,第二个成为值(如果它缺少值,最后一个Food 字也是如此,那么根本没有值-> 只是 undef。如何用 perl 做吗?

输出

Possible attempt to separate words with commas at ./a line 4.
Experimental push on scalar is now forbidden at ./a line 12, near ");"
Execution of ./a aborted due to compilation errors.

【问题讨论】:

    标签: perl hash push key-value


    【解决方案1】:

    我们可以将此数组分配给一个散列,perl 会自动查看数组中的值,就好像它们是键值对一样。奇数元素(第一、第三、第五)将成为键,偶数元素(第二、第四、第六)将成为相应的值。检查网址https://perlmaven.com/creating-hash-from-an-array

    use strict;
    use warnings;
    use Data::Dumper qw(Dumper);
    
    my @ar;
    my %hash;
    
    #The code in the enclosing block has warnings enabled, 
    #but the inner block has disabled (misc and qw) related warnings.
    {
        #You specified an odd number of elements to initialize a hash, which is odd, 
        #because hashes come in key/value pairs.
         no warnings 'misc';
         #If your code has use warnings turned on, as it should, then you'll get a warning about 
         #Possible attempt to separate words with commas
         no warnings 'qw';
         @ar = qw[Animals,dog Money,pound Jobs,doctor Food];
         # join the content of array with comma => Animals,dog,Money,pound,Jobs,doctor,Food
         # split the content using comma and assign to hash
         # split function returns the list in list context, or the size of the list in scalar context.
         %hash = split(",", (join(",", @ar)));
    }
    
    print Dumper(\%hash);
    

    输出

    $VAR1 = {
              'Animals' => 'dog',
              'Money' => 'pound',
              'Jobs' => 'doctor',
              'Food' => undef
            };
    

    【讨论】:

      【解决方案2】:

      map 内部拆分并直接分配给一个哈希,如下所示:

      my @ar = qw[Animals,dog Money,pound Jobs,doctor Food];
      my %hash_new = map { 
                            my @a = split /,/, $_, 2; 
                            @a == 2 ? @a : (@a, undef) 
                         } @ar;
      

      请注意,这也可以处理具有多个逗号分隔符的情况(因此最多拆分为 2 个元素)。这也可以处理没有逗号的情况,例如Food - 在这种情况下,返回具有单个元素加上undef 的列表。

      如果您需要 push 多个键/值对到(另一个)散列,或合并散列,您可以像这样分配散列列表:

      %hash = (%hash_old, %hash_new);
      

      请注意,旧哈希中的 same 键将被新哈希覆盖。

      【讨论】:

        【解决方案3】:

        我可能在这里过于简单化了,但为什么不简单地将散列分配而不是尝试推入它呢?

        即替换这个不支持的表达式:

        push %hash, ($ar2[0] => $ar2[1]);
        

        与:

        $hash{$ar2[0]} = $ar2[1];
        

        如果我在你的代码中加入这个,然后在最后转储生成的哈希,我会得到:

        $VAR1 = {
                  'Food' => undef,
                  'Money' => 'pound',
                  'Animals' => 'dog',
                  'Jobs' => 'doctor'
                };
        

        【讨论】:

        • 您还可以使用哈希切片一次执行多个操作 (@h{@keys} = @values;)
        猜你喜欢
        • 2011-04-16
        • 1970-01-01
        • 2019-08-21
        • 2014-06-27
        • 1970-01-01
        • 2015-05-24
        • 2022-08-24
        • 2017-03-07
        • 2012-02-20
        相关资源
        最近更新 更多