Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

When I have a list declared with my, it doesn't let use a symbolic reference to get to it. Here's my code:
#!/usr/local/bin/perl5.00503 @foo_list = (1,2,3); my @bar_list = (4,5,6); my $src = "foo"; my @list = @{"${src}_list"}; print "length = " . scalar @list . "\n"; $src = "pnotes"; @list = @{"${src}_list"}; print "length = " . scalar @list . "\n";
The output is:
length = 3 length = 0
What's the deal? Why do only non-my variables work?

Replies are listed 'Best First'.
Re: "my" variables don't work with symbolic
by davorg (Chancellor) on May 18, 2001 at 12:31 UTC

    <rant type="symbolic references">
    Symbolic references are bad.
    Don't use symbolic references.
    use strict prevents you from using symbolic references for a good reason.
    Read Dominus' article for more details on why symbolic references are a really bad idea.
    </rant>

    Do it like this instead:

    my %list; $list{foo} = [1, 2, 3]; $list{bar} = [4, 5, 6]; my $src = 'foo'; my @list = @{$list{$src}}; print 'length = ', scalar @list, "\n"; # or... $src = 'bar'; print 'length = ', scalar @{$list{$src}}, "\n";
    --
    <http://www.dave.org.uk>

    "Perl makes the fun jobs fun
    and the boring jobs bearable" - me

Re: "my" variables don't work with symbolic
by stephen (Priest) on May 18, 2001 at 08:11 UTC
    From perlman:perlref:
    Only package variables (globals, even if localized) are visible to symbolic references. Lexical variables (declared with my()) aren't in a symbol table, and thus are invisible to this mechanism.

    Which is another good reason to avoid them except in extreme and carefully-controlled circumstances...

    stephen