0

Hi all I got the problem that i cannot return the value and key in the hash of array

sub nextWords{
    for my $language(0 .. $#language )
    {
        my $eng = $db->selectall_arrayref("select word from words
            left outer join language
            on words.languageId = language.languageId
            where words.languageId = $language
            order by word asc
        ;"); # @language[$id] limit 10 offset $currentOffset

        #%returnArray2d = (@language[$language] =>[@$eng] );
        $returnArray2d{@language[$language]} = [@$eng];
    }
    return %returnArray2d;
}

I cannot really return all the list of words

my %newwordsList =NextWords();
    foreach my $key(keys %newwordsList)
    {
        print "here you are 2 : " . $key . "\n";
        for my $ind(0 .. @{$newwordsList{$key}}){
        print "dzo" . $newwordsList{$key}[$ind] . "\n";
    }
}

output: $key ==> 132 not 123

and the word cannot be printed.. it just prints some

ARRAY(0x320d514)
ARRAY(0x320d544)
ARRAY(0x320d574)
ARRAY(0x320d5a4)
ARRAY(0x320d5d4)
ARRAY(0x320d604)

Please help.. thanks

1 Answer 1

1

It looks like you're not setting up %returnArray2d correctly.

Assuming that @language contains the language ids you want, instead of:

$returnArray2d{ @language[$language] } = [@$eng];

You'll want this:

$returnArray2d{ $language[$language] } = [@$eng];

Also, you should avoid using the same name for an array and a scalar value (it works, but it's confusing) (see @language / $language in your code).

Lastly, you are correctly iterating through each key of %newwordsList, however, you will want to subtract 1 from the iteration, so that you don't go past the end of the array:

for my $ind ( 0 .. @{ $newwordsList{$key} } ) {

Should be:

for my $ind (0 .. @{ $newwordsList{$key} } - 1) {

Or (as David pointed out in the comments), you can do:

for my $ind ( 0 .. $#{ $newwordsList{$key} } ) {
Sign up to request clarification or add additional context in comments.

2 Comments

Also, in your print statements, this might work better for you: while (my ($language_id, $words) = each %newwordsList) { print "$language_id @$words\n"; }
Replace for my $ind ( 0 .. @{ $newwordsList{$key} } ) { with for my $ind ( 0 .. $#{ $newwordsList{$key} } ) { to avoid the fencepost error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.