I have a hash in a perl file (lets call it test2.pl) like so:
our %hash1;
my %hash2 = {
one => ($hash1{"zero1"}, $hash1{"one1"} ),
two => ($hash1{"one1"}, $hash1{"two1"} ),
three => ($hash1{"two1"}, $hash1{"three1"}),
four => ($hash1{"three1"}, $hash1{"six1"} ),
five => ($hash1{"six1"}, $hash1{"one2"} ),
six => ($hash1{"one2"}, $hash1{"two2"} ),
last => ($hash1{"two2"}, $hash1{"last1"} ),
};
This is getting 6 Use of uninitialized value in anonymous hash ({}) at test2.pl line 7. errors (line 7 in the file corresponds to the my %hash2 line and all the errors say line 7).
I can only assume this is because %hash1 is defined in another file (test1.pl) which calls this file. I thought using our would be enough to define it. Do I have to initialise all the variables in the hash for this to work?
(I’m using brackets with the our as there are other variables I have declared there.)
In Perl, you define hashes as even lists. That means that they are delimited by parens not braces:
Curly braces create a new anonymous hash reference.
If you wan’t to access the hash from another file, you should use a
packagedeclaration at the top:We can then
requireoruseyour file (although the filename and package name should preferably be the same) and access your hash as a package global:In your main file:
See the
Exportermodule for a nicer way use data structures in another namespace.