using no strict "refs"

B

Billy Patton

Here is a very small example of a larger amount of code.
use strict;
use warnings;
my $sub;

Pkg::a();
Pkg::b();
Pkg::c();

foreach $sub ( qw(a b c)) {
no strict "refs";
Pkg::${sub}(); <<<<< line 11
}


package Pkg;
use strict;
use warnings;
use Exporter;
sub a { print "a\n";}
sub b { print "b\n";}
sub c { print "c\n";}

In the real code a,b,c get called with data
I get the following after trying to execute:
Bad name after Pkg:: at x line 11.
 
P

Paul Lalli

Billy said:
Here is a very small example of a larger amount of code.
use strict;
use warnings;
my $sub;

Pkg::a();
Pkg::b();
Pkg::c();

foreach $sub ( qw(a b c)) {
no strict "refs";
Pkg::${sub}(); <<<<< line 11
}

You're trying to use a variable as a variable name (subroutines are
just another kind of variable, for our purposes here). Please read:
`perldoc -q "variable name"`

The way to do what you're trying to do is: &{"Pkg::$sub"}();

The RIGHT way to do it is to use a hash, and not disable strict refs:

my %sub_named = (
a => \&Pkg::a,
b => \&Pkg::b,
c => \&Pkg::c
);

foreach $sub ( qw(a b c)) {
$sub_named{$sub}->();
}


Paul Lalli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top