in reply to Understanding a OOP Code: Package declared within a Package

Hi sachinz2,

Packages can be declared (nearly) anywhere. A package declaration changes the current package name/namespace, and the new namespace is independent of the previous one, even if it's declared "within" another package - except that the two lexical scopes can overlap. In the case of OO, names do not matter - a class/package named "Foo::Bar" is not automatically related to "Foo" in any way, nor is a class/package declared within another class/package automatically related to its outer class, again except in the lexical scope (note that normal sub definitions/calls don't cross the package boundary via the lexical scope, as shown in the example below). The only way to establish an OO relationship is via @ISA and its helpers like base and parent. I'd suggest you have a look at package as well as "Packages" and "Symbol Tables" in perlmod, and then have a look at this example:

#!/usr/bin/env perl use warnings; use strict; our $pack = __PACKAGE__; # $main::pack print "$pack\n"; # prints "main" package Foo; our $pack = __PACKAGE__; # $Foo::pack print "$pack\n"; # prints "Foo" package Bar; our $pack = __PACKAGE__; # $Bar::pack print "$pack\n"; # prints "Bar" yak(); # defined below, prints "yak: Bar" package Foo::Bar; our $pack = __PACKAGE__; # $Foo::Bar::pack print "$pack\n"; # prints "Foo::Bar" sub yak { # Foo::Bar::yak() print "yak: ".__PACKAGE__."\n" } yak(); # prints "yak: Foo::Bar" { package Foo; # now back to package "Foo", nested in a new block our $blah = __PACKAGE__; # $Foo::blah print "$blah\n"; # prints "Foo" print "$Foo::pack\n"; # $Foo::pack is still "Foo" print "$Bar::pack\n"; # and $Bar::pack is still "Bar" # however, "$pack" access the most recent lexical definition print "$pack\n"; # so this is actually $Foo::Bar::pack, "Foo::Bar" # yak(); # but this doesn't work, there is no Foo::yak! { package Bar; # and back in package "Bar" # but we're still in the most recent lexical scope print "$pack\n"; # so this is still $Foo::Bar::pack, "Foo::Bar +" print "$blah\n"; # and this is still $Foo::blah, "Foo" sub yak { # Bar::yak() print "yak: ".__PACKAGE__."\n" } yak(); # prints "yak: Bar" } }

If you have further questions, I'd suggest you ask them with code to illustrate your question (see for example Short, Self Contained, Correct Example and How do I post a question effectively?).

Hope this helps,
-- Hauke D

Updated: Minor updates to wording for clarification.