How do I use an index in an array reference as a method reference in Perl?
- by Robert P
Similar to this question about iterating over subroutine references, and as a result of answering this question about a OO dispatch table, I was wondering how to call a method reference inside a reference, without removing it first, or if it was even possible.
For example:
package Class::Foo;
use 5.012; #Yay autostrict!
use warnings;
# a basic constructor for illustration purposes....
sub new {
my $class = shift;
return bless {}, $class;
}
# some subroutines for flavor...
sub sub1 { say 'in sub 1' }
sub sub2 { say 'in sub 2' }
sub sub3 { say 'in sub 3' }
# and a way to dynamically load the tests we're running...
sub sublist {
my $self = shift;
return [
$self->can('sub1');
$self->can('sub3'};
$self->can('sub2');
];
}
package main;
my $instance = Class::Foo->new(a => 1, b => 2, c => 3);
my $tests = $instance->sublist();
my $index = int(rand($#{$tests}));
# <-- HERE
So, at HERE, we could do:
my $ref = $tests->{$index};
$instance->$ref();
but how would we do this, without removing the reference first?