View Single Post
  #3 (permalink)  
Old 03-13-2012, 05:07 PM
Bill M
Guest
 
Posts: n/a
Default Re: getting hash reference from a package

Tim McDaniel wrote, On 3/13/2012 12:56 PM:
> In article<jjntgq$an4$1@dont-email.me>,
> Bill M<wpmccormick@just_about_everywhere.com> wrote:
>> Bill M wrote, On 3/13/2012 11:28 AM:
>>> What is the correct syntax for accessing a hash reference from a package?
>>>
>>> For example:
>>>
>>> package MyPackage;
>>> my $foo = {
>>> animals => ["cat", "dog", "fish"],
>>> people => ["fred", "wilma" ]
>>> };
>>>
>>> 1;

>
> I added the missing double-quote before wilma and lowercased
> "package".
>
> "1;" usually comes at the end of a module file. So I assume that
> that's in its own file, named MyPackage.pm.
>
>> use MyPackage;

> Yeah, that requires a separate source file named MyPackage.pm or such.
>>
>> foreach my $animal (@{$MyPackage::foo->{animals}}) {
>> print $animal;
>> }

>
> Realize that "my" is lexical only.
>
> (1) "my" does not create a package variable. There is no
> $MyPackage::foo variable in MyPackage. When you refer to it in the
> other file, it creates on that spot a variable set to undef.
>
> (2) It's lexical only, so it exists only inside the file's scope.
> It's not visible outside, so trying to refer to just "$foo" would get
> you an error "Global symbol "$foo" requires explicit package name".
>
> So replace "my" by "our" in MyPackage and it all works as you expect.
>

Thanks, just figured it out then saw your answer as I was about to reply
to myself.
Reply With Quote