[Israel.pm] require issue

Gaal Yahas gaal at forum2.org
Wed Feb 28 05:53:09 PST 2007


On Sun, Feb 25, 2007 at 12:22:27PM +0200, Levenglick Dov-RM07994 wrote:
> I have a main script that has 'use strict' enabled. In this script I
> define my %hash.  The I use eval{require "initialization_file.pl"}; to
> initialize %hash. When printing the hash keys I get a null string.
> 
> Initalization_file.pl states:
> %hash = (a=>,A, b=>B);
> 
> What is the problem (obviously a stupid one which I am overlooking)?

This has little directly to do with use strict.

The entity named %hash in the main script is lexically scoped, that is,
the name '%hash' only means that variable from the lexical scope of the
my declarator. Specifically, code in another file can't say '%hash' and
talk about the same memory.

In initialization_file.pl, presumbly you didn't have use strict on, so
when you said '%hash' you were talking about a package global, belonging
to whatever namespace initialization_file.pl was in ('main::' by
default). No other declaration would have helped; the original '%hash'
is not acceissible by name outside its scope. Had you said 'my %hash' in
initialization_file.pl, you'd have been talking about another '%hash' in
that scope; if you'd have said 'our %hash' or 'use vars qw(%hash)' or
even '%main::hash' you'd still have been talking about a different
entity from the original.

One immediate fix is to change the declarator in the main script to
'our'. This changes its type to a global! Another WTDI is to hand over a
reference to the %hash container to the initialization module; yet
another is to have the module return the initialized value and assign
it. The right thing to do depends on the size of the data, how you're
going to be accessing it, how complex you want your code to be, etc.

-- 
Gaal Yahas <gaal at forum2.org>
http://gaal.livejournal.com/



More information about the Perl mailing list