How do I use an index in an array reference as a method reference in Perl?

Posted by Robert P on Stack Overflow See other posts from Stack Overflow or by Robert P
Published on 2010-05-10T15:50:29Z Indexed on 2010/05/10 15:54 UTC
Read the original article Hit count: 245

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about perl

Related posts about reference