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

Greetings Wise Monks, I have a novice question. I would like to do the following but seems like I am missing something minor.
my $temp_2 = "foo"; my $temp_3 = "bar"; for ($i = 2; $i < 4; $i++) { print ${"temp_$i"},"\n"; }
Is this possible, and how can I make it work? Thanks for your help in advance!
  • Comment on dynamically picking up Hashes or variables based on argument passed.
  • Download Code

Replies are listed 'Best First'.
Re: dynamically picking up Hashes or variables based on argument passed.
by FunkyMonk (Bishop) on Nov 19, 2007 at 21:20 UTC
    The best way is to use a hash:
    my %temps = ( temp_2 => "foo", temp_3 => "bar" ); for my $i ( 2 .. 3 ) { print $temps{"temp_$i"}, "\n"; }

    Notice that I changed your for loop into something a little more perlish.

    untested: my Perl box broke :(

      Thanks everyone! The link was helpful too!
Re: dynamically picking up Hashes or variables based on argument passed.
by Corion (Patriarch) on Nov 19, 2007 at 21:14 UTC
Re: dynamically picking up Hashes or variables based on argument passed.
by Roy Johnson (Monsignor) on Nov 19, 2007 at 21:15 UTC