Brendan L. Brendan L. - 2 months ago 14
Perl Question

Perl MindMelting uninitialized variable in scalar from array exception

I had a hard time titleing this question, as I am truly stumped as to what could be causing this error.

when I have the code typed as such:

my @strArray= ('TypeKey', 'AccidentType', '01');
my %HashArrayThing = ('EnglishArray' => @strArray,
'FrenchArray' => ('julier', 'aout', 'septembre'));
my $scalar = @HashArrayThing{EnglishArray};
my @ARR = @HashArrayThing{EnglishArray};
say $scalar,
say $ARR[0];

the output is:


when I change ONLY the
say $ARR[0]
say $ARR[1]
(or any other number) I get the error: "Uninitialized value in say at line 50"(same line as the 'say $scalar')

This makes no sense to me. I could understand that the $ARR[1] could be out of bounds having maybe olny gotten the first value from the array stored in the hashset, but I don't understand at all where this is coming from.
I hope there is someone out there with a thourough understanding of perl who can enlighten me.

PS. also where is the '1'coming from that is bieng added to typekey.


This line:

my %HashArrayThing = ('EnglishArray' => @strArray, 
    'FrenchArray' => ('julier', 'aout', 'septembre'));

is actually creating this structure:

      'AccidentType' => '01',
      'FrenchArray' => 'julier',
      'EnglishArray' => 'TypeKey',
      'aout' => 'septembre'

where I imagine you were expecting:

      'FrenchArray'  => ['julier', 'aout', 'septembre'],
      'EnglishArray' => ['TypeKey', 'AccidentType', '01'],

This is happening because the value of a key/value pair in a Hash must be a SCALAR. So it is a simple value like a number or a string or a reference to Hash or an Array.

The following is the correct way to initialize your Hash:

my %HashArrayThing = (
    'EnglishArray' => [@strArray], 
    'FrenchArray'  => ['julier', 'aout', 'septembre']

Notice that the arrays you passed in previously are now wrapped in [] which creates a reference to an array.