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

I've been struggling with this for about an hour and I feel like I am dancing around the answer, but just not getting it. You can see I have problems understanding references...

I pass over an array in a for loop and want to stuff values into a defined hash. The hash being called is created from a value within the array

for my $i(@asnValues) { my @asnParams = split(/ /,$i); my $asnHash = "asn$asnParams[0]"; }

I'd then like to put other array values into this hash within the same for loop

$$asnHash{risk} = $queueNsp[2];

I receive the error about can't use string as hash ref while strict refs. So I tried

my $asn = "asn$asnParams[0]"; my $asnHash = \%{$asn};

but still it was a no go. Can someone please school me on the correct manner of doing this? I'll beat it into my skull by day's end.

thanks very much -c

Replies are listed 'Best First'.
Re: Calling a hash through an array value
by dragonchild (Archbishop) on Jan 08, 2003 at 21:17 UTC
    Bad c! No cookie! We do not use symbolic references.

    Instead, make a hash of hashes (or HoH). So, do something like:

    my %asn; for my $i (@asnValues) { my @asnParams = split / /, $i; my $keyName = $asnParams[0]; $asn{$keyName}{risk} = $queueNsp[2]; }
    Treat it as you would a 2-D array in C or BASIC or JAVA or any other language. The only difference is that you don't have to pre-declare it. Perl does that for you on the fly. (If you don't need or want to know how, then just assume it will work and go about your business.)

    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      Well, of course we can use symbolic references - when it's the right thing to do.

      But here it's not.

      Here is a detailed explanation (Dominus article) for why dragonchild bit your head off.

Re: Calling a hash through an array value
by OM_Zen (Scribe) on Jan 08, 2003 at 23:09 UTC
    Hi ,
    $UniverseOfHashes{$asnHash}{risk} = $queueNsp[2];

    should be in the loop . You are trying to get the reference of hash to have a key of $asnHash and not the Hash itself which is symbolic and not the referred Hash by itself , Hece should use the second element as the key of the hash itself .