Search code examples
perlperl-data-structures

Perl hashref printing keys


I have the following hashref :-

my $hashref = {'a'=>(1,2,3,4),
               'b'=>(5,6,7,8)};

then I use the following to just print the keys (i.e. 'a' and 'b') :-

foreach (keys %$hashref){
   print "\n".$_."\n";
}

This prints the following output:-

4

a

7

2

5

Trying to print the datastructure hashref using Data::Dumper gives the following output:-

$VAR1 = {
          '4' => 'b',
          'a' => 1,
          '7' => 8,
          '2' => 3,
          '5' => 6
       };

My question is :-

1) How to just print the correct keys i.e. 'a' and 'b'. 2) Why does the data structure look like the one in the above output and not like:-

$VAR1 = {
           'a' => (1,2,3,4),
           'b' => (5,6,7,8)
        };

Solution

  • You are defining the hash wrong. It interprets this:

    'a'=>(1,2,3,4),
    'b'=>(5,6,7,8)
    

    as simply a list of 10 elements. (Remember that a hash can also be declared using a simple list, the => operator is optional.) Instead, use square brackets to make your values into arrayref literals:

    'a'=>[1,2,3,4],
    'b'=>[5,6,7,8]
    

    Which Data::Dumper should call:

    $VAR1 = {
       'a' => [1,2,3,4],
       'b' => [5,6,7,8]
    };