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

I am trying to use a for loop to retrieve two keys and two specific values from each key. These values are then saved to a variable for later use. Here is an example of what I have so far:
for ($i=0; $i<2; $i++) { $graphic.$i = $pers_dcr_files{$key[$i]}{GraphicName}; $url.$i = $pers_dcr_files($key[$i]}{url}; }
I know that my syntax is wrong, what I am trying to do is retrieve two keys (file names) and assign two values from each to a variable that changes name every time the loop runs. What is the correct syntax for this type of operation? Or any suggestions on a better way to do this? Thanks, Bill

Replies are listed 'Best First'.
Re: How to I retrieve a specific key/value from a hash?
by Masem (Monsignor) on May 15, 2001 at 19:56 UTC
    You can create variable with names based on strings via the following mechanism:
    ${ $graphic.$i } = $pers_dcr_files{ $key[$i] }{GraphicName};
      I was just reading an excellent article by Dominus on why you shouldn't do that. Since you only have two variables, it's not going to hurt you to flatten that loop:
      $graphic1 = $pers_dcr_files{ $key[1] }{GraphicName}; $graphic2 = $pers_dcr_files{ $key[2] }{GraphicName};
      Probably run faster and be easier to maintain that way, too. If you need more variables, use a hash:
      for $i (1..10) { $graphic{$i} = $pers_dcr_files{ $key[$i] }{GraphicName}; }
      You have to reference it as $graphic{1} instead of $graphic1, but that doesn't seem like a real big problem.
Re: How to I retrieve a specific key/value from a hash?
by aijin (Monk) on May 15, 2001 at 22:23 UTC
    Basically what you're trying to do is create similarly named variables, right? It looks like you're trying to concatenate the base for the variable name with the number, and that's not going to work. You could use an associative array...especially since you seem to be using numbers as the differentiating factor in your naming scheme.

    Thus, you can go about it like this:

    my (%graphic, %url); for ($i=0; $i<2; $i++) { $graphic{$i} = $foo; $url{$i} = $bar; }

    Then when you wish to print, say, the second graphic, you would use:

    print $graphic{2};

    Hope this was of some help to you.