简体   繁体   English

Perl:将值添加到匿名哈希

[英]Perl: Adding values to anonymous hash

There is something like this 有类似的东西

my $labels = {
   1  => 'One',     2  => 'Two',
   3  => 'Three',   4  => 'Four',
   5  => 'Five',    6  => 'Six',
   7  => 'Seven',   8  => 'Eight',
   9  => 'Nine',    10 => 'Ten',
};

I want to generate the same thing in a "For-Loop" with variables. 我想在带有变量的“For-Loop”中生成相同的东西。

    my $labels;
    my @dData = ( "One" , "Two", "dynamic Data", .. );
    my $index = @ddData;

            for(my $i = 0; $i < $index; $i++){
                            $labels{$i} = $dData[$i];

            }

But the result is always: 但结果总是:

Use of uninitialized value $labels in concatenation (.) or string

There are three main errors here 这里有三个主要错误

  • Your array is called dData , not ddData . 你的数组称为dData ,不ddData You should always use strict and use warnings at the start of every program. 您应始终在每个程序的开头use strictuse warnings This simple measure would have picked up your mistake 这个简单的措施可以解决你的错误

  • Your index $i starts from zero, but it seems that you want your hash keys to start at one 你的索引$i从零开始,但似乎你希望你的哈希键从一开始

  • To access a hash by reference you need to use the indirection operator 要通过引用访问哈希,您需要使用间接运算符

Fixing these problems gives 解决这些问题给出了

use strict;
use warnings;

my $labels;
my @dData = ( "One" , "Two", "dynamic Data");
my $index = @dData;

for (my $i = 0; $i < $index; $i++) {
  $labels->{$i+1} = $dData[$i];
}

use Data::Dump;
dd $labels;

output 产量

{ 1 => "One", 2 => "Two", 3 => "dynamic Data" }

It is also far better to enumerate the elements of a loop, rather than use a C-style for loop. 枚举循环元素也好得多,而不是使用C风格for循环。 This would have been better written as 这本来写得更好

$labels->{$_+1} = $dData[$_] for 0 .. $#dData;

The code you posted doesn't compile with use strict; 您发布的代码不use strict;编译use strict; and should be giving you additional warnings (for example, you use @dData in one line and @ddData in the next). 并应给你额外的警告(例如,您使用@dData在一行和@ddData在未来)。 I would use the following: 我会使用以下内容:

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

my $hashref;
my @data = qw(One Two Three Four);

foreach my $i (0 .. $#data) {
    $hashref->{$i+1} = $data[$i];
}

print Dumper $hashref;

Output: 输出:

$VAR1 = { 
          '4' => 'Four',
          '1' => 'One',
          '3' => 'Three',
          '2' => 'Two'
        };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM