in reply to Re: Perlish dice for gamers (oh, and importing autoloaded functions)
in thread Perlish dice for gamers (oh, and importing autoloaded functions)

Inheriting Exporter is good! :)

hossman wrote:

Can anybody out there think of a way to genuinely create an entry the symbol table for a package that points to "AUTOLOAD" ?

I was in the middle of typing why this couldn't be done, when I talked myself into a way of trying it! What do you think of this?

sub import { no strict 'refs'; my $pkg = shift; for my $dice (@_) { if ($dice =~ /r(\d+)[Dd](\d+)/) { # my $meth = \sub { roll($1, $2); }; my $meth = \sub {"__PACKAGE__::$dice"}; *{$pkg . '::' . $dice} = $meth; } } @EXPORT_OK = @_; Smonk->export_to_level(1, $pkg, @_); }
  • Comment on Re: Re: Perlish dice for gamers (oh, and importing autoloaded functions)
  • Download Code

Replies are listed 'Best First'.
Re: Re: Re: Perlish dice for gamers (oh, and importing autoloaded functions)
by hossman (Prior) on Sep 10, 2002 at 04:07 UTC
    my $meth = \sub {"__PACKAGE__::$dice"};
    *{$pkg . '::' . $dice} = $meth;
    Ya know, i stared at that for about 20 minutes trying to figure out why it worked. It seemed to me that all the first line should do is create an anonymous sub that returns "__PACKAGE__::$dice" ... so i did some digging, and sure enough that *IS* all it does.

    I don't know what you and I have been doing wrong with our attempts at putting things in the package's symbol table, but evidently none of it was doing anything (at least: not anything that affected what we were testing).

    It turns out that THIS is all you need to import an AUTOLOADed method...

    sub import { my $pkg = shift; @EXPORT_OK = @_; __PACKAGE__->export_to_level(1, $pkg, @_); }

    But for the sake of correctness, it should probably only copy things into @EXPORT_OK that match the regexp -- that way writting "use Smonk qw(r3d3 foo)" will generate...

    "foo" is not exported by the Smonk module at monk.pl line 4 Can't continue after import errors at monk.pl line 4 BEGIN failed--compilation aborted at monk.pl line 4.
      I don't know what you and I have been doing wrong...

      Looks like we were making it harder than it is =)

      Thanks to hossman for the discussion.
      Thanks to blakem for the function-naming pointer.
      Apologies for the grossly-oversized node name, which I have since learned is an annoyance.