in reply to Calling a subroutine when part of call is a variable Contant
You can simply put a methods name into a variable, here $meth and call it dynamically
use strict; use warnings; use Data::Dump; my $o = new Class; my $count=0; for my $meth (qw/foo bar baz/) { $o->$meth($count++); } package Class; sub new { return bless {} } sub foo { my $self =shift; warn "foo: @_\n" } sub bar { my $self =shift; warn "bar: @_\n" } sub baz { my $self =shift; warn "baz: @_\n" }
out
foo: 0 bar: 1 baz: 2
If you have problems using a constant in this syntax, then why not simply copy it first into a variable? This will certainly improve readability.
NB: Readonly should work anyway!
HTH! :)
Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Je suis Charlie!
and if you rather prefer unreadable syntax
my %meth = ( foo => "foo" ); $o->${\ $meth{foo} }($count++);
this answers your original question:
use constant { STUFF => { 'BAR' => 'bar', }, }; my $key = "BAR"; $o->${ \ STUFF->{$key} }($count++);
Perl needs to see a $-sigil to accept a symbolic method name, that's why deref of a scalar ref ${ \ "bar" } is a workaround.
But you forgot to put the $key part inside the deref
|
|---|