in reply to Interpolating an array element as a hash name.

Your brain is still doing C, C++, Java, whatever you used to do before perl.

While C style for loops do work in Perl, it's better to think of loops in terms of lists, arrays, sets:

for my $i ( 0..2 ) { for my $j ( 0..2 ) { ... } }

But why do you have these hashes named $a{0}, $a{1}, $a{2}? Those sound like arrays, not hashes. In fact, I kept accidentally using square brackets instead of curlies, and then had to repair them.

Better yet, why not start thinking in meaningful terms, for example %expense, %income, %profits over the keys qw( January February March .... ). Hmmm ... still sounds like arrays.

What are you really trrying to achieve? As opposed to how you think you need to implement it ...?

--
TTTATCGGTCGTTATATAGATGTTTGCA

Replies are listed 'Best First'.
Re: Re: Interpolating an array element as a hash name.
by yam (Novice) on Mar 15, 2004 at 13:27 UTC
    Thanks for the style tip. Yes, started out in C and I'm still getting used to thinking in perl.

    As far as the array names, they were used for ease of input for this problem only. Their real names look like: $high_price, $low_price, etc.

    As to what I want to achieve; the data I'm reading in consists of a file with many different sets of input all smashed together. Ten years of a stock's high price then ten years of a stock's low price and then ten years of a stock's something else, etc. I figured that using an array with the elements in order of their appearance in the data would make it easy for me to get to by reading the index of the array and multiplying by 10 (number of years) and then doing a loop to add the data into the hash ($high_price{1995}=52.50).

    I'm writing my first, uh, program with perl. I'm a system administrator and I live off of one-liners and one-off scripts, so my ability to do this in perl is being stretched.

    Again, thanks for your help,
    - chris

      Names with modifiers are an indicator that you should be using a hash instead of separate variables. Instead of $price_high, it might be an idea to use $price{high}.

      How about something like ...

      open STOCKS, ">", $dataFileName or die $!; my $price; PRICES: for my $category ( qw( high low average purple green ) ) { for my year ( 1990..2000 ) { last PRICES unless $price = <STOCKS>; # break loop at eof. $prices{$category}{$year} = $price; } }

      --
      TTTATCGGTCGTTATATAGATGTTTGCA