Can a function tell which module it was called from? - perl

package Bar;
use Foo;
sub bar { fooit "hello from bar"; }
package Foo;
sub fooit {
# Somehow I want this function to know it was called
# from the "Bar" module (in this case).
}
Preferably, this would be done without explicitly passing an argument containing the calling module's name.

The builtin caller function can be used to get information about the current call stack.
sub fooit {
my ($pkg, $file, $line) = caller;
print STDERR "fooit was called from the $pkg package, $file:$line\n";
}

caller with no argument in scalar context will return the caller's namespace.
my $caller = caller();
or
print caller()."\n"; # '.' forces scalar context
or
print "".caller(), "\n"; # '.' forces scalar context
It's very rare that you need that, unless you're trying to replicate the behaviour of one of Carp's subs.

Using the builtin caller should be the easiest and the most straightforward way to do this, but Devel::Backtrace is also a worth to see CPAN module, which can provide more detail information with an elegant interface.
package Foo;
use Devel::Backtrace;
sub fooit {
my $backtrace = Devel::Backtrace->new;
print $backtrace->point(1)->package, "\n\n";
print $backtrace;
}
package Bar;
sub bar {
Foo::fooit('hello from bar');
}
package main;
Bar::bar();
Output:
Bar
Devel::Backtrace::new called from Foo (test.pl:5)
Foo::fooit called from Bar (test.pl:14)
Bar::bar called from main (test.pl:19)

Related

Getting wrong argument value when trying to call a subroutine using PackageName::ModuleName->subroutine("xyz")in perl

When trying to call a subroutine (defined in a user defined module) in other perl file, getting wrong argument value
#moduleName.pm
package PackageName::moduleName;
use strict;
use warnings;
use base 'Exporter';
sub callMe{
my($readArg)=(#_);
print $readArg;
}
#test.pl
use strict;
use warnings;
use FindBin; # locate this script
use lib 'path to parent directory'; # use the parent directory
use PackageName::moduleName;
if( my $temp=PackageName::moduleName->callMe("test")){
print" True : $temp\n";
}
The function prints value of $temp as : PackageName::moduleName
Not able to figure out why.
P.S. I have to maintain same convention while calling the subroutine
You are calling a function as a class method with Foo::Bar->frobnicate(#args). In that case, Perl will do the following things because of the arrow ->:
check what's on the left of the arrow
if it's blessed, find the package (e.g. $q is package CGI)
if it's not blessed, assume it's a package (e.g. Foo::Bar)
within that package namespace, find a sub with the name on the right of the arrow (e.g. frobnicate)
call that sub and pass what's on the left of the arrow as the first argument
Now it looks like this:
Foo::Bar::frobnicate('Foo::Bar', #args);
In frobnicate, you have to deal with that:
sub frobnicate {
my ($class, #args) = #_;
# ...
}
That's typically done in a new, which is the most likely use of a class method.
If you don't want to deal with it, call the sub directly in its namespace, and not with the arrow notation.
my $rv = Foo::Bar::frobnicate(#args);
Because of the way you're calling it via ->.
When you do this, perl passes extra arguments, so you can make a constructor (new).
E.g.
my $thing = Package::Module -> new();
The first argument passed is the class, so you can use that for a bless. See:
perlootut
E.g.
sub new {
my ( $class, #args ) = #_;
my $self = {};
bless ( $self, $class );
}
This also applies when you call an instantiated object:
$thing -> do_something();
It passes a reference to $self as the first argument.
sub do_something {
my ( $self, #args ) = #_;
print "Got args of #args\n";
$self -> {firstarg} = shift ( #args );
}
If you want to do that, try instead:
PackageName::ModuleName::callMe("test");

What is the domain of a reference function called in a perl module?

I would like to pass function reference to a perl module as follows.
Here is the main program:
#main.pl
use module;
my $ref = sub {
# what if a function is called or an array asked?
# is domain main:: or module::?
print "Log $date ", #_, "\n"
} ;
define_log_function($ref);
And here is the module:
# module.pm
package module;
my $log ;
sub define_log_function {
$log = shift;
}
sub other_function {
$log and &$log("Calling other_function");
(...)
}
What is the domain of the log function called inside my module? What happens if I try to call a function inside my module? Is its domain "main::" or "module::"?
Thank for your time.
Every subroutine belongs to a certain package, even when it's an anonymous sub. The following code will print Foo Foo:
use feature 'say';
package Foo;
my $coderef = sub {
say __PACKAGE__;
foo();
};
sub foo { say "Foo" }
package Bar;
sub foo { say "Bar" }
$coderef->();
It doesn't matter that the $coderef is executed inside the Bar package because it was compiled inside the Foo package. Not only subroutines, but also other global variables are looked up in the package where the code was compiled in.
Note that you can switch into another package whenever you want, for the rest of the lexical scope:
my $coderef = sub {
say __PACKAGE__;
package Bar;
foo();
};
would give Foo Bar.
$ref lexical variable (defined with my) and holds reference to closure. Lexicals doesn't belong to namespace, only global variables can be accessed like $module::package_global.

How can I get the name of the current subroutine in Perl?

In Perl we can get the name of the current package and current line number Using the predefined variables like __PACKAGE__ and __LINE__.
Like this I want to get the name of the current subroutine:
use strict;
use warnings;
print __PACKAGE__;
sub test()
{
print __LINE__;
}
&test();
In the above code I want to get the name of the subroutine inside the function test.
Use the caller() function:
my $sub_name = (caller(0))[3];
This will give you the name of the current subroutine, including its package (e.g. 'main::test'). Closures return names like 'main::__ANON__'and in eval it will be '(eval)'.
caller is the right way to do at #eugene pointed out if you want to do this inside the subroutine.
If you want another piece of your program to be able to identify the package and name information for a coderef, use Sub::Identify.
Incidentally, looking at
sub test()
{
print __LINE__;
}
&test();
there are a few important points to mention: First, don't use prototypes unless you are trying to mimic builtins. Second, don't use & when invoking a subroutine unless you specifically need the effects it provides.
Therefore, that snippet is better written as:
sub test
{
print __LINE__;
}
test();
I was just looking for an answer to this question as well, I found caller as well, but I was not interested in the fully qualified path, simply the literal current package name of the sub, so I used:
my $current_sub = (split(/::/,(caller(0))[3]))[-1];
Seems to work perfectly, just adding it in for if anyone else trips over this questions :)
There special __SUB__ exists from perl-5.16.
use v5.16;
use Sub::Identify qw/sub_fullname/;
sub foo {
print sub_fullname( __SUB__ ); # main::foo
}
foo();
Actually you can pass to sub_fullname any subroutine reference (even anonymous):
use Sub::Identify qw/sub_fullname/;
sub foo {
print sub_fullname( \&foo ); # main::foo
print sub_fullname( sub{} ); # main::__ANON__
}
foo();

How does an object access the symbol table for the current package?

How could I access the symbol table for the current package an object was instantiated in? For example, I have something like this:
my $object = MyModule->new;
# this looks in the current package, to see if there's a function named run_me
# I'd like to know how to do this without passing a sub reference
$object->do_your_job;
If in the implementation of do_your_job I use __PACKAGE__, it will search in the MyModule package. How could I make it look in the right package?
EDIT:I'll try to make this clearer. Suppose I have the following code:
package MyMod;
sub new {
return bless {},$_[0]
}
sub do_your_job {
my $self = shift;
# of course find_package_of is fictional here
# just for this example's sake, $pkg should be main
my $pkg = find_package_of($self);
if(defined &{ $pkg . '::run_me' }) {
# the function exists, call it.
}
}
package main;
sub run_me {
print "x should run me.\n";
}
my $x = MyMod->new;
# this should find the run_me sub in the current package and invoke it.
$x->do_your_job;
Now, $x should somehow notice that main is the current package, and search it's symbol table. I tried using Scalar::Util's blessed , but it still gave me MyModule instead of main. Hopefully, this is a bit clearer now.
You just want caller
caller tells you the package from which it was called. (Here I added some standard perl.)
use Symbol qw<qualify_to_ref>;
#...
my $pkg = caller;
my $symb = qualify_to_ref( 'run_me', $pkg );
my $run_me = *{$symb}{CODE};
$run_me->() if defined $run_me;
To look it up and see if it's defined and then look it up to call it would duplicate it as standard perl doesn't do Common Subexpression Elimination, so you might as well 1) retrieve it, and 2) check definedness of the slot, and 3) run it if it is defined.
Now if you create an object in one package and use it in another, that's not going to be too much help. You would probably need to add an additional field like 'owning_package' in the constructor.
package MyMod;
#...
sub new {
#...
$self->{owning_package} = caller || 'main';
#...
}
Now $x->{owning_package} will contain 'main'.
See perldoc -f caller:
#!/usr/bin/perl
package A;
use strict; use warnings;
sub do_your_job {
my ($self) = #_;
my ($pkg) = caller;
if ( my $sub = $pkg->can('run_me') ) {
$sub->();
}
}
package B;
use strict; use warnings;
sub test {
A->do_your_job;
}
sub run_me {
print "No, you can't!\n";
}
package main;
use strict; use warnings;
B->test;
Output:
C:\Temp> h
No, you can't!

How do I loop over all the methods of a class in Perl?

How do you loop over all the methods of a class in Perl? Are there any good online references to Perl introspection or reflection?
The recommendation Todd Gardner gave to use Moose is a good one, but the example code he chose isn't very helpful.
If you're inspecting a non-Moose using class, you'd do something like this:
use Some::Class;
use Class::MOP;
my $meta = Class::MOP::Class->initialize('Some::Class');
for my $meth ( $meta->get_all_methods ) {
print $meth->fully_qualified_name, "\n";
}
See the Class::MOP::Class docs for more details on how to do introspection.
You'll also note that I used Class::MOP instead of Moose. Class::MOP (MOP = Meta-Object Protocol) is the base on which Moose builds. If you're working with non-Moose classes, using Moose to introspect doesn't gain you anything.
If you wanted, you could use Moose () and Moose::Meta::Class->initialize instead of CMOP.
You can easily get a list of the defined methods of a class using the answers already provided. However, Perl is a dynamic language, which means more methods may be defined later. There really isn't a way to get a list of all of the methods to which any particular class will handle. For a lot more detail on this sort of stuff, I have a few chapters in Mastering Perl.
People are giving you (and upvoting) answers without telling you about the limitations.
Adam mentions his Class::Inspector, but it doesn't really work because it's trying to do something a dynamic language doesn't do (and that's be static :) For instance, here's a snippet where Class::Inspector returns no methods, but I can still call the VERSION method (as well as isa and can):
BEGIN {
package Foo;
our $VERSION = '1.23'
}
use Class::Inspector;
my $methods = Class::Inspector->methods( 'Foo' );
print "Methods are [#$methods]\n"; # reports nothing
print Foo->VERSION, "\n";
Here's another case where I can call any method I like, but Class::Inspector only returns AUTOLOAD (and still missing VERSION, isa, and can):
BEGIN {
package Foo;
our $VERSION = '1.23';
my $object = bless {}, __PACKAGE__;
sub AUTOLOAD { $object }
}
use Class::Inspector;
my $methods = Class::Inspector->methods( 'Foo' );
print "Methods are [#$methods]\n"; # reports only "AUTOLOAD"
print Foo->dog->cat->bird, "\n";
Curiously, everyone seems to ignore UNIVERSAL, probably because they don't explicitly handle it since it's only virtually in #ISA. I can add a debug method to every class, and Class::Inspector still misses it even though it's a defined method:
BEGIN {
sub UNIVERSAL::debug { "Hello debugger!\n" }
package Foo;
}
use Class::Inspector;
my $methods = Class::Inspector->methods( 'Foo' );
print "Methods are [#$methods]\n"; # still reports nothing
print Foo->debug, "\n";
Class::MOP has the same limitations.
Not every module is going to use AUTOLOAD, but it's not an obscure or rare feature either. If you don't mind that you are going to miss some of the methods then Class::Inspector or Class::MOP might be okay. It's just not going to give you a list of every method you can call on a class or an object in every case.
If you have a class or an object and you want to know if you can call a particular method, use can(). Wrap it in an eval block so can can call can() on things that aren't even objects to still get back false, instead of death, in those cases:
if( eval { $object->can( 'method_name' ) } )
{
$object->( #args );
}
In the general case, you'll have to inspect the symbol table (unless you use Moose). For example, to list the methods defined in the IO::File package:
use IO::File;
no strict 'refs';
print join ', ', grep { defined &{"IO::File::$_"} } keys %{IO::File::};
The hash %{IO::File::} is the symbol table of the IO::File package, and the grep filters out non-subroutine entries (e.g. package variables).
To extend this to include inherited methods, you have to recursively search the symbol tables of the parent classes (#IO::File::ISA).
Here is a complete example:
sub list_methods_for_class {
my $class = shift;
eval "require $class";
no strict 'refs';
my #methods = grep { defined &{$class . "::$_"} } keys %{$class . "::"};
push #methods, list_methods_for_class($_) foreach #{$class . "::ISA"};
return #methods;
}
For more info on packages and symbol tables, see the perlmod man page.
Depends if you mean, any class, or if you were implementing your own. For the latter, I use Moose, which offers a very clean syntax for these features. From the cookbook:
my %attributes = %{ $self->meta->get_attribute_map };
for my $name ( sort keys %attributes ) {
my $attribute = $attributes{$name};
if ( $attribute->does('MyApp::Meta::Attribute::Trait::Labeled')
# ... keeps on
You probably want Class::Inspector->methods('Your::Class').
Nuff said.
I'll just leave this here for when I forget it. This is extremely powerful; too bad it is so out of the way that most Perl programmers never get to experience it.
package Foo;
use strict;
sub foo1 {};
sub foo2 {};
our $foo3 = sub{};
my $foo4 = "hello, world!";
package Bar;
use strict;
# woo, we're javascript!
(sub {
*Bar::foo1 = sub { print "hi!"; };
*Bar::foo2 = sub { print "hello!"; };
$Bar::foo1 = 200;
})->();
package main;
use strict;
use Data::Dumper;
$Data::Dumper::Deparse = 1;
print Dumper \%Data::Dumper::;
print Dumper \%Foo::;
print Dumper \%Bar::;