Array values not being processed

Question!

I tried to implement a hash, and its key "Foo Bar" has an array as its value. While I tried to assign hash with this specific key to an array,the resultant array is not working as expected:

 use strict;
 use warnings;
 use Data::Dumper qw(Dumper);

 my %grades;
 $grades{'Foo Bar'}[0] = 23;
 $grades{'Foo Bar'}[1] = 42;
 $grades{'Foo Bar'}[2] = 73;
 my @array = $grades{'Foo Bar'};

 foreach my $myval ( @array )
 {
         print $myval;
 }

Where exactly has it gone wrong?



Answers

The hash value is a reference to an array, a scalar value. Copying it into an array as you have done results in an array with one element equal to the array reference

You need to dereference the value to access the referenced array. You can dereference it directly like this

for my $val ( @{ $grades{'Foo Bar'} } ) {
    print $val, "\n";
}

Or you can copy it into a scalar variable first, as I show in my code below

use strict;
use warnings 'all';

my %grades;

$grades{'Foo Bar'}[0] = 23;
$grades{'Foo Bar'}[1] = 42;
$grades{'Foo Bar'}[2] = 73;

my $array = $grades{'Foo Bar'};

for my $val ( @$array ) {
    print $val, "\n";
}

output

23
42
73
By : Borodin


This video can help you solving your question :)
By: admin