1

I have a lot of functions starting with a given prefix. I would like to create an array of these functions and then execute them one by one.

Consider:

use v5.12;

my @names = qw(a b);
my @ss = map { "s".$_ } @names;

sub sa {
    say "a";
}

sub sb {
    say "b";
}

Here the function prefix is s. How do I call these functions one by one, for instance, using a for loop..? (I tried inserting a \& inside the map command, but that did not work.)

Note that all the functions will take the same arguments, and that's why I think this is something that could be useful to do...

2 Answers 2

4

One possible approach:

use 5.012;

my @names = qw(a b);
my @ss    = map { \&{"s$_"} } @names;

sub sa {
    say "a";
}

sub sb {
    say "b";
}

&$_() for @ss;

Demo. In short, references to the functions are stored. Note that storing subroutine names in @ss and calling those (with & sygil) fails in the strict mode:

Can't use string ("sa") as a subroutine ref while "strict refs"

And, perhaps it's just me, but I'd rather define these functions in a hash:

my %hof = (
  a => sub { say 'a'; },
  b => sub { say 'b'; },
  c => sub { say 'c: ' . $_[0]; },
);

$hof{$_}('something') for sort keys %hof;

output

a
b
c: something
Sign up to request clarification or add additional context in comments.

Comments

2
use strict;
use warnings;
use v5.12;

use Data::Dumper;

my @names = qw(a b);
my @ss = map { $main::{"s$_"} } @names;

$_->() for @ss;


sub sa {
    say "a";
}

sub sb {
    say "b";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.