in reply to How to call sub defined in a variable?

In the context of OO code you could:

use strict; use warnings; my $self = bless {tests => [qw(something else another bogus)]}; for my $testName (@{$self->{tests}}) { my $test = $self->can ("test_$testName"); if (! $test) { warn "Test $testName not available\n"; next; } print "Running test $testName:\n"; $test->($self); } print "Testing complete\n"; sub test_something { print "something\n"; } sub test_else { print "something else\n"; } sub test_another { print "another unimaginative statement\n"; }

Prints:

Running test something: Test bogus not available something Running test else: something else Running test another: another unimaginative statement Testing complete

which allows derived classes to add tests that are managed by the parent class.


Perl's payment curve coincides with its learning curve.

Replies are listed 'Best First'.
Re^2: How to call sub defined in a variable?
by chromatic (Archbishop) on Jan 25, 2009 at 22:12 UTC

    Usually the lack of distinction between function and method is a problem in Perl, but here it means that you can use can() on a package name even if it's not a class and get back a subroutine reference even if it's not a method.

    package My::Awesome::Package; use 5.010; sub foo { ... } sub bar { ... } sub baz { ... } package main; for my $func (qw( foo bar baz quux )) { next unless my $func_ref = My::Awesome::Package->can( $func ); say "Found code for '$func': ", $func->(); }