N
niall.macpherson
I have a hash within which I want each element to conatin a reference
to an array . I have checked perldoc perldsc but for some reason cannot
seem to get the syntax for pushing a new element onto the array.
The 'push' line in the code attached fails to compile with 'Global
symbol "$testhash" requires explicit package name at
C:\develop\NiallPerlScripts\clpm10.pl line 34.' and although I have
tried a number of different syntaxes.
Also is there way I can do without the
if(!defined($testhash{$key}{"myarray"}));
line ? I know that if I am assigning a scalar value I can just do
$testhash{$key}{"myscalar"} = 123;
and autovivfication will take care of this but I can't figure out how
to autovivfy a hash element if it contains an array reference.
use strict;
use warnings;
use Data:umper;
my %testhash;
while(<DATA>)
{
chomp;
if(/(\d*)\s*(\d*)/)
{
my($key, $val) = ($1, $2);
## Using $testhash{$key}{myarray} = <array>
## rather than $testhash{$key} = <array> since in
## my real world prog there is other stuff in the hash
## in addition to the array which is unique to the key
## Do I need to test this ?
if(!defined($testhash{$key}{"myarray"}))
{
$testhash{$key}{"myarray"} = [$val];
}
else
{
## What is correct syntax here ?? This line won't compile
## From perldoc perldsc
## append new members to an existing family
## push @{ $HoA{"flintstones"} }, "wilma", "betty";
push @{ $testhash{$key}{"myarray"}}, $val;
}
}
}
print Dumper $testhash;
__END__
123 45
456 777
789 999
123 111
123 222
to an array . I have checked perldoc perldsc but for some reason cannot
seem to get the syntax for pushing a new element onto the array.
The 'push' line in the code attached fails to compile with 'Global
symbol "$testhash" requires explicit package name at
C:\develop\NiallPerlScripts\clpm10.pl line 34.' and although I have
tried a number of different syntaxes.
Also is there way I can do without the
if(!defined($testhash{$key}{"myarray"}));
line ? I know that if I am assigning a scalar value I can just do
$testhash{$key}{"myscalar"} = 123;
and autovivfication will take care of this but I can't figure out how
to autovivfy a hash element if it contains an array reference.
use strict;
use warnings;
use Data:umper;
my %testhash;
while(<DATA>)
{
chomp;
if(/(\d*)\s*(\d*)/)
{
my($key, $val) = ($1, $2);
## Using $testhash{$key}{myarray} = <array>
## rather than $testhash{$key} = <array> since in
## my real world prog there is other stuff in the hash
## in addition to the array which is unique to the key
## Do I need to test this ?
if(!defined($testhash{$key}{"myarray"}))
{
$testhash{$key}{"myarray"} = [$val];
}
else
{
## What is correct syntax here ?? This line won't compile
## From perldoc perldsc
## append new members to an existing family
## push @{ $HoA{"flintstones"} }, "wilma", "betty";
push @{ $testhash{$key}{"myarray"}}, $val;
}
}
}
print Dumper $testhash;
__END__
123 45
456 777
789 999
123 111
123 222