dgBP
dgBP

Reputation: 1691

Can I use hash values from another file?

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.)

Upvotes: 1

Views: 2178

Answers (1)

amon
amon

Reputation: 57600

In Perl, you define hashes as even lists. That means that they are delimited by parens not braces:

my %hash = (
  key1 => "value1",
  key2 => "value2",
);
my $anonHashRef = {
  key1 => "value1",
  key2 => "value2",
};

Curly braces create a new anonymous hash reference.

If you wan't to access the hash from another file, you should use a package declaration at the top:

package FooBar;
# Your %hash comes here
# it HAS to be GLOBAL, i.e. declared with `our`, not `my`

We can then require or use your file (although the filename and package name should preferably be the same) and access your hash as a package global:

In your main file:

use 'file2.pl';
my $element = $FooBar::hash{$key};

See the Exporter module for a nicer way use data structures in another namespace.

Upvotes: 6

Related Questions