Jonathan H.
Jonathan H.

Reputation: 816

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.

    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

Upvotes: 1

Views: 1057

Answers (2)

Borodin
Borodin

Reputation: 126722

There are three main errors here

  • Your array is called dData, not ddData. You should always use strict and use warnings at the start of every program. 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

  • 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. This would have been better written as

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

Upvotes: 2

ThisSuitIsBlackNot
ThisSuitIsBlackNot

Reputation: 24063

The code you posted doesn't compile with use strict; and should be giving you additional warnings (for example, you use @dData in one line and @ddData in the next). 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'
        };

Upvotes: 1

Related Questions