Search code examples
arraysperlperl-data-structures

How do I create a 2D array in Perl?


I am trying to create a 2d array in Perl

my code:

my @wordsList=();
my @words=();

for ($id=0; $id<[email protected]; $id++)
{

        my $eng = $db->selectall_arrayref("select word from words 
                                                    left outer join language
                                                    on words.languageId = language.languageId
                                                    where words.languageId = $id
                                                    ;");


        foreach $eng(@$eng)
        {   
        my($word) = @$eng;
        $ref_to_Array->[$id][$word] = @words($id,$word);

            }
                return $words($id, $word);
}

$wordsList= NextWords();
print $wordsList;

it returns non.. because I want to return the 2d array.

Update

I am still confused because when I execute the query, it gives me a list of words like :

select word from words where language_id = 1 
(1=english, 2 - chinese, 3 - french) 

I am using the for loop through the language and in order to get all the words from the database

The problem is I want to loop and want the array is added to the 2d array automatically.


Solution

  • Place use warnings; use strict; at the top of every program you write. Those two pragmas will catch many errors for you.

    You can't access an array with a (...) postfix. That construct is used to call functions mysub(...) or $mysubref->(...). To access array elements, you use a postfix [ index ]. And in Perl, multi-dimensional arrays require a pair of [...] for each level. This is because a 2D array is simply an array where each element is also an array.

    my @array = ([1, 2, 3], [4, 5, 6], [7, 8, 9]);
    
    my $top_left     = $array[0][0];  # 1
    my $bottom_right = $array[2][2];  # 9
    
    print "@$_\n" for @array;
    
    1 2 3
    4 5 6
    7 8 9
    

    You can learn more about Perl's data structures and the rest of Perl at perldoc.perl.org. Here are a few direct links:

    Finally, @language.length does not do what you think it does. It is taking @language in scalar context, which is its length as a number and then concatenating it with length($_). The resulting expression is something like (scalar @language) . length($_). Since the <= operator imposes scalar context on its arguments, you could simply write $id <= @language. However, Perl provides you with a more natural way of writing this type of loop:

    for my $id (0 .. @language) {...}
    

    or

    for my $id (0 .. $#language) {...}
    
    if you really meant $id < @language since $language[scalar @language] is one element past the end of the array.