december has asked for the wisdom of the Perl Monks concerning the following question:

Hey fellow monks,

I have a question about scope in packages and I hope somebody smarter and with deeper knowledge of Perl internals can explain the resulting error messages to me.

Given the following simplified code:

#!/usr/bin/perl -wT use warnings; use strict; # call object method Animal::Hog->sound(); # here we define the object { package Animal::Hog; my $sound1 = "knor1"; our $sound2 = "knor2"; sub new() { my $this = shift; my $class = ref($this) || $this; my $self = {}; bless $self; return $self; } sub sound() { my $self = shift; print $sound1, "\n"; print $sound2, "\n"; return 'knor'; } }

... I get this result:

Use of uninitialized value $sound1 in print at ./ line 30. Use of uninitialized value $Animal::Hog::sound2 in print at ./ l +ine 31.

I am wondering why Perl knows about Animal::Hog->sound() without predeclaring it, yet returns an error for the lexical variables $sound1 and $sound2. It confuses me because I expect Perl to either have parsed the section and declared the variables and functions, or for it to not have done so and hence not know about any variables or functions in that block at all.


Thanks for any insight!

PS: I know I could move the package declaration above the invocation, use a BEGIN block or declare the objects in another file.