JWM:

You rarely want to have a variable name itself be variable, for many good reasons. If you don't know how to do it, you probably don't really want it. (I'll insert a link to a node that describes the technique and caveats as soon as I [id://Super Search|find it] again. Also, I'm not being snotty, I don't know how to do it either.)

However, the technique described by madbombX and mreece is usually the best way to do the job. Here's a quickie example on how to use the technique:

#!/usr/bin/perl -w use strict; use warnings; my %hr = ( 'default' => [ 1 .. 9], 'even' => [ 0, 2, 4, 6, 8], 'odd' => [ 1, 3, 5, 7, 9], ); my $arrname = shift || 'default'; print "Array $arrname contains:\n"; my $ar = $hr{$arrname}; for my $cnt (0 .. $#{$ar}) { printf "\t %s[%d]=%s\n", $arrname, $cnt, $ar->[$cnt]; }

Running this yields:

roboticus@swill ~/PerlMonks $ ./var_array_names.pl even Array even contains: even[0]=0 even[1]=2 even[2]=4 even[3]=6 even[4]=8 roboticus@swill ~/PerlMonks $ ./var_array_names.pl odd Array odd contains: odd[0]=1 odd[1]=3 odd[2]=5 odd[3]=7 odd[4]=9

--roboticus

UPDATE: Yarch! I was a bit slow, and several people beat me to the punch. Oh, well. Anyway, here are links to a few of the threads describing the pro & cons:

  • variable with $$ see response Re: variable with $$!
  • Dynamically Building Variable Names
  • construct variable name on the fly by aquarium
  • Variable name containing a variable
  • and the list goes on and on...

    In reply to Re: Array of Arrays with Variable Names by roboticus
    in thread Array of Arrays with Variable Names by JWM

    Title:
    Use:  <p> text here (a paragraph) </p>
    and:  <code> code here </code>
    to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.