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

I have a list of variables named the same except for an incremented number appended to the name. I wish to do a loop and print out these variables. How do I reference the variable names? (The variable name can be output using "blah" . $i; how do I get to the contents of that variable?) thanks

Replies are listed 'Best First'.
Re: generating variable names
by btrott (Parson) on Feb 23, 2000 at 04:57 UTC
    It sounds like you're asking about symbolic references. You can use symbolic references, but there are a lot of disadvantages associated with using them.

    I think a better way of approaching such a problem would be to use an array or a hash. Something like this:

    my @blah = qw/foo bar baz/; # where you would have accessed "blah" . $i, you can # now access $blah[$i] instead for my $i (0..$#blah) { print $blah[$i], "\n"; } # or you can just foreach foreach my $thing (@blah) { print $thing, "\n"; }
Re: generating variable names
by Anonymous Monk on Feb 23, 2000 at 12:37 UTC
    Dynamically generate the code and eval() it. For example: for $i (0..10) { my $code = "\$blah" . $i; print eval($code); } But, of course btrott is right. You might want to think about using arrays or hashes.
RE: generating variable names
by dlc (Acolyte) on Feb 24, 2000 at 00:11 UTC
    Make life easier on yourself and use either a hash or an array, so that it can be accessed via indexes or keys.