in reply to How do I call a sub using a variable as its name, objectively

Choroba showed you how to do it, however allowing calls to arbitrary functions can be a bit of a security hole. To get around that I usually decorate the sub name after the user has provided it:

use strict; use warnings; package My; sub new { my ($class) = @_; return bless {}, $class; } sub ext_show { my ($self, $name) = @_; print "Hello $name!\n"; return 1; } package main; my $A = 'My'->new(); my $method = 'ext_' . shift; $A->$method(@ARGV);

Prints:

Hello Bob!

when given the command line parameters show Bob. Because 'ext_' is added a prefix to the actual name it's not possible for the user to call an unintended sub.

Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

Replies are listed 'Best First'.
Re^2: How do I call a sub using a variable as its name, objectively
by ysth (Canon) on Oct 28, 2024 at 23:21 UTC
    Or use a whitelist:
    my $A = My::->new(); my $method = $method_list{$ARGV[0]} or die "Invalid method $ARGV[0]."; $A->$method(@ARGV[1..$#ARGV]);
    --
    A math joke: r = | |csc(θ)|+|sec(θ)| |-| |csc(θ)|-|sec(θ)| |

      I have done that in the past, but the list, the implementation and the documentation all have to be updated. Using the prefix trick avoids the need to update the list. I admit, a fairly minor point, but it does reduce scope for error.

      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond