But I'd like to point you towards caller too, where you can find out what package a sub has been called from.
sub test { my($pkg) = caller; print "I've been called from package $pkg\n"; } package Foo; main::test(); __END__ I've been called from package Foo
Note that you can get more extensive information, as well as finding out about deeper calling levels, if you use an integer parameter to caller. For this application, caller() and caller(0) would yield the same results.
Also,I want to know "how to access the package" by name or by it's associated variables.You mean, how to access variables from a different package? Like this:
If you want to access variables of which you just found out the package name, there are several ways, a stash (from "Symbol Table hASH", which is what it is) being the low level (but hard) approach — in particular, deeper level package names like Foo::Bar are hard to access. There's an excellent chapter in the 1st edition of the O'Reilly book "Advanced Perl Programming" about stashes.$Foo::x # scalar @Foo::y # array %Foo::z # hash $Foo:z{bar} # hash item # etc.
But the easy approach is to use symbolic references. That's how Exporter does it. Note that you'll temporarily have to disable use strict;.
my $pkg = "Foo"; my $var = "x"; $Foo::x = 123; { no strict 'refs'; print ${$pkg . '::' . $var}; } __END__ prints: "123";
In reply to Re: How to know current Package
by bart
in thread How to know current Package
by perladdict
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |