Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re^2: Dynamic Package Name & Subroutine Call

by tobyink (Abbot)
on Dec 15, 2012 at 07:57 UTC ( #1008944=note: print w/replies, xml ) Need Help??


in reply to Re: Dynamic Package Name & Subroutine Call
in thread Dynamic Package Name & Subroutine Call

An alternative to no strict 'refs' would be:

foreach my $pkg ( @pkgs ) { my $hello = "Test::$pkg"->can('hello'); $hello->() if $hello; }

... because can returns a coderef. In the case of packages that have inheritance (@ISA) this will act slightly differently to &{'Test::' . $pkg . '::hello'}().

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Replies are listed 'Best First'.
Re^3: Dynamic Package Name & Subroutine Call
by ikegami (Pope) on Dec 16, 2012 at 13:57 UTC

    can should be used for methods and only for methods, so that should be

    my $full_pkg = "Test::".$pkg; my $hello = $full_pkg->can('hello'); $full_pkg->$hello(...); # Or: $hello->($full_pkg, ...);

    which simplifies to:

    my $full_pkg = "Test::".$pkg; $full_pkg->hello(...);

    You don't even need can if the method name is variable.

    $full_pkg->$method_name(...);

      can should be used for methods and only for methods

      that boat has sailed a long time ago :)

        That makes no sense. This isn't a change; can has never done the right thing for non-methods.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1008944]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2018-01-23 02:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How did you see in the new year?










    Results (238 votes). Check out past polls.

    Notices?