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

In my quest to improve QuizTaker.pl, I am trying to modify it, so that it can
accept questions that are a combination of multiple choice and true/false. What I
need to accomplish this (I think), is to be able to read the length of array that is
the value of a key within a hash. I have a small test function below, but it doesn't
quite work. It merely gives the memory address of the array. Any suggestions?
#!/usr/bin/perl -w use strict; my @value1=(1,2,3,4); my @value2=(5,6); my @value3=(7,8,9,0); my %Hash = (Key1=>\@value1,Key2=>\@value2,Key3=>\@value3); my @hasharraylengths=(); my $length = 0; foreach my $key (keys %Hash){ $length = $Hash{$key}; push @hasharraylengths, $length; } my $l = @hasharraylengths; for(my $x=0;$x<$l;$x++){ print"Length of Value: $hasharraylengths[$x]\n"; }

TStanley
In the end, there can be only one!

Replies are listed 'Best First'.
Re: Array length within a hash
by suaveant (Parson) on Apr 23, 2001 at 21:37 UTC
    either
    $length = $#{$Hash{$key}}+1; # I think will work # or $length = @{$Hash{$key}}; #I know will work
    you must dereference the arrayref
                    - Ant
Re: Array length within a hash
by arturo (Vicar) on Apr 23, 2001 at 21:42 UTC

    Try

    foreach my $key (keys %Hash) { push @hasharraylengths, scalar @{$Hash{$key}}; }

    The idea : $Hash{$key} is an array reference. Dereference, with @{}, and force scalar ccntext with scalar.

    HTH

Re: Array length within a hash
by ton (Friar) on Apr 23, 2001 at 21:39 UTC
    Replace this line:
    $length = $Hash{$key};
    with this line:
    $length = @{$Hash{$key}};
    Remember that you're storing references to the arrays as the values of your hash. You need to dereference those values...

    -Ton
    -----
    Be bloody, bold, and resolute; laugh to scorn
    The power of man...

Re: Array length within a hash
by the_0ne (Pilgrim) on Apr 23, 2001 at 21:40 UTC
    I think this is what you are getting at TStanley...

    foreach my $key (keys %Hash){ $length = $#{$Hash{$key}} + 1; push @hasharraylengths, $length; }

    The output should be...

    Length of Value: 4
    Length of Value: 2
    Length of Value: 4