...mainly, I feel like you aren't really AUTOLOADing anything. Your import method is using eval to dynamicly create the method -- at that point it exists, and the AUTOLOAD isn't needed. (unless you add some direct calls to Games::Dice->foo, but even then: the eval called by your AUTOLOAD is dynamicly creating the method, after the first invokation, your AUTOLOAD won't be used.
I tweaked your code some (see below), mainly to replace the eval in the AUTOLOAD with a call out to a new "roll" method, and the eval in your import with some direct symbol table munging.
The problem is, This still isn't "importind autoloaded functions" ... anything a client tries to import, is acctually created at import time.
Can anybody out there think of a way to genuinely create an entry the symbol table for a package that points to "AUTOLOAD" ?
(PS: I changed the name from "Games::Dice" to "Smonk" to protect the innocent.)
#!/usr/bin/perl package main; use Smonk ( 'r3d6' ); use strict; use warnings; my %rolls; for (1..100) { my $roll = r3d6; $rolls{$roll}++; } for (1..100) { my $roll = Smonk->r3d6; $rolls{$roll}++; } for (sort {$a<=>$b} keys %rolls) { print "$_ => $rolls{$_}\n"; } ##### Smonk.pm ########################### package Smonk; use warnings; use strict; use vars qw($AUTOLOAD @ISA @EXPORT_OK); @ISA = qw(Exporter); sub roll { my ($rolls, $di) = @_; my $result = $rolls; for( my $i = 0; $i < $rolls; $i++ ) { $result += int(rand($di)); } return $result; } sub AUTOLOAD { my $self = shift; if ( $AUTOLOAD =~ /^.*::r(\d+)[Dd](\d+)/ ) { return roll($1, $2); } } sub import { no strict 'refs'; my $pkg = shift; for my $dice (@_) { if ($dice =~ /r(\d+)[Dd](\d+)/) { my $meth = \sub { roll($1, $2); }; *{$pkg . '::' . $dice} = $meth; } } @EXPORT_OK = @_; Smonk->export_to_level(1, $pkg, @_); } 1;
In reply to Re: Perlish dice for gamers (oh, and importing autoloaded functions)
by hossman
in thread Perlish dice for gamers (oh, and importing autoloaded functions)
by Solo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |