FAQ 7.29 How can I use a variable as a variable name?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
This is an excerpt from the latest version perlfaq7.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .


7.29: How can I use a variable as a variable name?

    Beginners often think they want to have a variable contain the name of a

            $fred    = 23;
            $varname = "fred";
            ++$$varname;         # $fred now 24

    This works *sometimes*, but it is a very bad idea for two reasons.

    The first reason is that this technique *only works on global
    variables*. That means that if $fred is a lexical variable created with
    my() in the above example, the code wouldn't work at all: you'd
    accidentally access the global and skip right over the private lexical
    altogether. Global variables are bad because they can easily collide
    accidentally and in general make for non-scalable and confusing code.

    Symbolic references are forbidden under the "use strict" pragma. They
    are not true references and consequently are not reference counted or
    garbage collected.

    The other reason why using a variable to hold the name of another
    variable is a bad idea is that the question often stems from a lack of
    understanding of Perl data structures, particularly hashes. By using
    symbolic references, you are just using the package's symbol-table hash
    (like %main::) instead of a user-defined hash. The solution is to use
    your own hash or a real reference instead.

            $USER_VARS = 23;
            $varname = "fred";
            $USER_VARS++;  # not $$varname++

    There we're using the %USER_VARS hash instead of symbolic references.
    Sometimes this comes up in reading strings from the user with variable
    references and wanting to expand them to the values of your perl
    program's variables. This is also a bad idea because it conflates the
    program-addressable namespace and the user-addressable one. Instead of
    reading a string and expanding it to the actual contents of your
    program's own variables:

            $str = 'this has a $fred and $barney in it';
            $str =~ s/($\w+)/$1/eeg;                 # need double eval

    it would be better to keep a hash around like %USER_VARS and have
    variable references actually refer to entries in that hash:

            $str =~ s/$(\w+)/$USER_VARS/g;   # no /e here at all

    That's faster, cleaner, and safer than the previous approach. Of course,
    you don't need to use a dollar sign. You could use your own scheme to
    make it less confusing, like bracketed percent symbols, etc.

            $str = 'this has a %fred% and %barney% in it';
            $str =~ s/%(\w+)%/$USER_VARS/g;   # no /e here at all

    Another reason that folks sometimes think they want a variable to
    contain the name of a variable is because they don't know how to build
    proper data structures using hashes. For example, let's say they wanted
    two hashes in their program: %fred and %barney, and that they wanted to
    use another scalar variable to refer to those by name.

            $name = "fred";
            $$name = "wilma";     # set %fred

            $name = "barney";
            $$name = "betty"; # set %barney

    This is still a symbolic reference, and is still saddled with the
    problems enumerated above. It would be far better to write:

            $folks   = "wilma";
            $folks = "betty";

    And just use a multilevel hash to start with.

    The only times that you absolutely *must* use symbolic references are
    when you really must refer to the symbol table. This may be because it's
    something that can't take a real reference to, such as a format name.
    Doing so may also be important for method calls, since these always go
    through the symbol table for resolution.

    In those cases, you would turn off "strict 'refs'" temporarily so you
    can play around with the symbol table. For example:

            @colors = qw(red blue green yellow orange purple violet);
            for my $name (@colors) {
                    no strict 'refs';  # renege for the block

    All those functions (red(), blue(), green(), etc.) appear to be
    separate, but the real code in the closure actually was compiled only

    So, sometimes you might want to use symbolic references to directly
    manipulate the symbol table. This doesn't matter for formats, handles,
    and subroutines, because they are always global--you can't use my() on
    them. For scalars, arrays, and hashes, though--and usually for
    subroutines-- you probably only want to use hard references.


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in

Re: FAQ 7.29 How can I use a variable as a variable name?

Quoted text here. Click to load it

This FAQ should probably mention that you *can* have a variable
containing a variable name, if you use eval, like this:

use strict;
use warnings;

my $foo="hello";
my $variable_name = 'foo';

print eval "$$variable_name", "\n";

or even like this:

use strict;
use warnings;

my $foo="hello";
my $variable_name = '$foo';

print eval($variable_name), "\n";

It should also mention that it's almost always a bad idea.

Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

Re: FAQ 7.29 How can I use a variable as a variable name?

  KT> It should also mention that it's almost always a bad idea.

agreed. my edit which could be put in is this:

Using a string for a variable name (via symbolic references or eval)
means you are using the symbol table (which is a specialized hash tree)
for a data structure. This has many flaws including action at a
distance, the inability to isolate your data and it is slower. Instead
you should just use your own data structures composed of hashes and
hash/array references. Read perllol and perldsc for more on how to do
this. The symbol table should only be modified if you are actually
manipulating symbols and not just your data.

(that can be improved upon i am sure. but the gist is pretty good IMO).

and yes, i know that eval can even access lexicals with strings for
names but that is even nastier than accessing globals!


Uri Guttman  ------  uri@stemsystems.com  --------  http://www.sysarch.com --
-----  Perl Code Review , Architecture, Development, Training, Support ------
--------- Free Perl Training --- http://perlhunter.com/college.html ---------
---------  Gourmet Hot Cocoa Mix  ----  http://bestfriendscocoa.com ---------

Re: FAQ 7.29 How can I use a variable as a variable name?

Quoted text here. Click to load it

I need to rewrite this answer anyway, so I'll consider how to at once
tell people how to do it and not to do it. :)

Site Timeline