[Thamesvalley-pm] perl subroutine refs

Stephen Cardie stephenca at ls26.net
Tue Nov 13 14:19:36 PST 2007



ed wrote:
> Hi,
>
> I'm trying to do something to compare scriptable plugin methods between
> php and perl, but I have a problem in that I cannot figure out how to
> do it with strict:
>
> #!/usr/bin/perl
>
> use warnings;
> use strict;
>
> my %subs;
>
> sub test {
> 	print( "Tested\n" );
> }
>
> my $l = "test";
>
> $subs{'plugname'} = &$l;
> $subs{'plugname'};
>
> The error message insists that this is not possible while using strict
> refs, but I'd like to be able to continue using everything that strict
> offers, is there a 'safe' way to do this?
>   

ed,

This won't work under strict() because you are attempting to create a 
symbolic reference (see perldoc perlref).  If you really, really want to 
do this, you need

no strict qw(refs);

But you don't want to do that ...

One "safe" way to do this is with a despatch table; basically, a hash of 
anonymous subs.

my(%despatch) = (
    test => sub { print "Tested\n" },
);

# later ...
my(%subs);
$subs{plugname} = 'test';
$despatch{$subs{plugname}}->();

# ...
__END__

Cheers,

Steve




More information about the Thamesvalley-pm mailing list