http://qs321.pair.com?node_id=885055


in reply to scope and declaration in local packages

Anorny is right. Let me illustrate by walking through your program in two passes. The first stage is the compilation stage. I've elided code that has no effect during compilation.

#!/usr/bin/perl -T # implicit BEGIN blocks cause require and importing use strict; use warnings; # here we define the object { # creates a namespace package Animal::Hog; # creates, but does not initialize, a lexical my $sound1; # creates, but does not initialize, a strict-friendly global our $sound2; # creates the function sub new { my $class = shift; bless {}, $class; } # creates the function, closing over the lexical $sound1 # ... and binding to the symbol $Animal::Hog::sound2 sub sound { my $self = shift; print $sound1, "\n"; print $sound2, "\n"; return 'knor'; } }

That's the compilation stage. Runtime looks like this, with irrelevant code elided:

#!/usr/bin/perl -wT # call object method Animal::Hog->sound(); { # assigns to the variable my $sound1 = "knor1"; # assigns to the variable our $sound2 = "knor2"; }

Execution happens in statement order.

(I also cleaned up your code slightly. Prototypes are useless on methods. Single-argument bless is almost always an error. The copy constructor technique using ref is also almost always an error.)