using no strict "refs"

Discussion in 'Perl Misc' started by Billy Patton, Jan 10, 2007.

  1. Billy Patton

    Billy Patton Guest

    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.
    Billy Patton, Jan 10, 2007
    #1
    1. Advertising

  2. Billy Patton

    Paul Lalli Guest

    Billy Patton wrote:
    > 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
    Paul Lalli, Jan 10, 2007
    #2
    1. Advertising

  3. Mumia W. (on aioe), Jan 11, 2007
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Guest

    sort and Sub Refs

    Guest, Jan 3, 2004, in forum: Perl
    Replies:
    1
    Views:
    707
    Guest
    Jan 3, 2004
  2. John Nagle
    Replies:
    3
    Views:
    289
    John Nagle
    Feb 25, 2007
  3. Daniel Friedman

    Q: "my" variables and "no strict 'refs'"

    Daniel Friedman, Jun 26, 2003, in forum: Perl Misc
    Replies:
    1
    Views:
    136
    Eric Schwartz
    Jun 26, 2003
  4. Noel Sant

    Array of hashes and strict refs - help!

    Noel Sant, Jan 30, 2004, in forum: Perl Misc
    Replies:
    4
    Views:
    258
    Ben Morrow
    Jan 30, 2004
  5. bpatton

    no strict 'refs' need help

    bpatton, Jul 12, 2007, in forum: Perl Misc
    Replies:
    1
    Views:
    123
    Brian McCauley
    Jul 12, 2007
Loading...

Share This Page