in reply to Re^6: Function name in a variable, can't recall the concept (introspection with ->can )
in thread Function name in a variable, can't recall the concept

> get_sub_by_name

which get_sub_by_name?

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

  • Comment on Re^7: Function name in a variable, can't recall the concept (introspection with ->can )

Replies are listed 'Best First'.
Re^8: Function name in a variable, can't recall the concept (introspection with ->can )
by Veltro (Hermit) on Apr 19, 2019 at 13:51 UTC

    He probably means something hypothetical...

    I was actually thinking about this seriously, and I would likely do something as:

    sub get_sub_by_name { my ($pkg, $name) = @_ ; no strict 'refs' ; if ( exists ${$pkg . '::'}{$name} ) { if ( ref ${$pkg . '::'}{$name} eq 'CODE' ) { return *{$pkg . '::' . $name} ; } } ; }

    Maybe it can be written more pretty, and I don't know if any odd-cases are trapped (e.g. what about __ANON__)

    edit: Comes to think of it, maybe the line 'exists' is not even needed?

      I'm afraid your hypothetical code for his hypothetical function is ignoring how typeglobs work.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

        Oh yeah, haha, what have I been smoking!

        I'll probably stick with this then:

        sub get_sub_by_name { my ($pkg, $name) = @_ ; no strict 'refs' ; if ( defined &{$pkg . '::'. $name} ) { return \&{$pkg . '::'. $name} ; } }
Re^8: Function name in a variable, can't recall the concept (introspection with ->can )
by ikegami (Patriarch) on Apr 19, 2019 at 18:03 UTC

    Some code that gets a reference to the sub by name. What that code is doesn't matter, though it could be as simple as \&{ $pkg . '::' . $name }.

      > could be as simple as \&{ $pkg . :: . $name }.

      nope, this will autovivify a missing function glob $name and return a broken coderef.

      try again.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

        You're missing the point. I'm not proposing a solution; I'm saying that yours is ludicrous. It makes absolutely no sense to use

        my $sub = @{ get_array_by_name($pkg, 'ISA') } ? get_sub_by_name($pkg, $name) : $pkg->can($name);

        instead of

        my $sub = get_sub_by_name($pkg, $name);

        The implementation of get_sub_by_name isn't relevant to that point.