Search code examples
perlperl-data-structures

Print 2 Dimensional Array in Loop Perl


This is how i append data into the array :

push @cordinate_and_link, ($cordinate , $link); 

So if i print @cordinate_and_link i get something like:

172193 1 19601 2 14835 3 4758 4 ...

I will like have a loop which can loop only the first column[0] and produce all values.

This is what i have been trying:

foreach my $cordinate ( $cordinate_and_link[0]) {
            print "$cordinate";
        } 

But this statement prints only the last value in the row "4758" as many times as the loop runs.


Solution

  • You are currently appending two values to @cordinate_and_link which sit next to each other – they are not in separate columns. To make clear that they are in two different columns, we push an anonymous arrayref [...] instead:

    push @cordinate_and_link, [$cordinate , $link]; 
    

    Parens () do not create arrays or tuples in Perl.

    Later, we can loop over all rows and only print the first column in each row:

    foreach my $cordinate (@cordinate_and_link) {
        print $cordinate->[0];
    }