| 1 | #!/usr/bin/perl -X | ||
| 2 | package AI::MicroStructure::List; | ||
| 3 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 1 | ▶ | use AI::MicroStructure (); # do not export microname and friends |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 5 | use AI::MicroStructure::RemoteList; | ||
| 6 | use List::Util qw( shuffle ); | ||
| 7 | use Carp; | ||
| 8 | |||
| 9 | our @ISA = qw( AI::MicroStructure::RemoteList ); | ||
| 10 | |||
| 11 | sub init { | ||
| 12 | my ($self, $data) = @_; | ||
| 13 | my $class = caller(0); | ||
| 14 | |||
| 15 | $data ||= AI::MicroStructure->load_data($class); | ||
| 16 | croak "The optional argument to init() must be a hash reference" | ||
| 17 | if ref $data ne 'HASH'; | ||
| 18 | |||
| 19 | no strict 'refs'; | ||
| 20 | no warnings; | ||
| 21 | ${"$class\::structure"} = ( split /::/, $class )[-1]; | ||
| 22 | @{"$class\::List"} = split /\s+/, $data->{names}; | ||
| 23 | *{"$class\::import"} = sub { | ||
| 24 | my $callpkg = caller(0); | ||
| 25 | my $structure = ${"$class\::structure"}; | ||
| 26 | my $micro = $class->new(); | ||
| 27 | *{"$callpkg\::micro$structure"} = sub { $micro->name(@_) }; | ||
| 28 | }; | ||
| 29 | ${"$class\::micro"} = $class->new(); | ||
| 30 | } | ||
| 31 | |||
| 32 | sub name { | ||
| 33 | my ( $self, $count ) = @_; | ||
| 34 | my $class = ref $self; | ||
| 35 | |||
| 36 | if( ! $class ) { # called as a class method! | ||
| 37 | $class = $self; | ||
| 38 | no strict 'refs'; | ||
| 39 | $self = ${"$class\::micro"}; | ||
| 40 | } | ||
| 41 | no strict 'refs'; | ||
| 42 | |||
| 43 | if( defined $count){ | ||
| 44 | if ($count == 0 ) { | ||
| 45 | return | ||
| 46 | wantarray ? shuffle @{"$class\::List"} : scalar @{"$class\::List"}; | ||
| 47 | } | ||
| 48 | } | ||
| 49 | $count ||= 1; | ||
| 50 | my $list = $self->{cache}; | ||
| 51 | { | ||
| 52 | no strict 'refs'; | ||
| 53 | if (@{"$class\::List"}) { | ||
| 54 | push @$list, shuffle @{"$class\::List"} while @$list < $count; | ||
| 55 | } | ||
| 56 | } | ||
| 57 | splice( @$list, 0, $count ); | ||
| 58 | } | ||
| 59 | |||
| 60 | sub new { | ||
| 61 | my $class = shift; | ||
| 62 | |||
| 63 | bless { cache => [] }, $class; | ||
| 64 | } | ||
| 65 | |||
| 66 | sub structure { | ||
| 67 | my $class = ref $_[0] || $_[0]; | ||
| 68 | no strict 'refs'; | ||
| 69 | return ${"$class\::structure"}; | ||
| 70 | } | ||
| 71 | |||
| 72 | |||
| 73 | |||
| 74 | |||
| 75 | 1; | ||
| 76 | |||
| 77 | __END__ | ||
| 78 | |||