nish
nish

Reputation: 7280

Creating an array of arrays in perl

How can I create an array of arrays in perl and access each of the member arrays with an appropriate index.

Currently I'm using a one dimensional array, updating it at each iteration and printing:

for ($i=0;$i<$size;$i++)
{
  @words = @synsets[$i]->words;
  print "@words\n"
}

But since at the next step i want to perform further operations, I want to access arrays corresponding to each "synset". Could someone please tell me how i could do that?

Upvotes: 3

Views: 4870

Answers (3)

G. Cito
G. Cito

Reputation: 6378

Here's a small self-contained files to demonstrate the basics. Edit to suit :-)

Data::Dumper helps with visualizing data structures - a great learning tool.

The [] acts as an "anonymous array constructor". You can read more about that with perldoc perlref (or follow the previous link). Sometimes you have to explain something to someone else before you can be even somewhat sure you understand it yourself, so bear with me ;-)

use 5.10.0 ;
use Data::Dump;
use strict;
use warnings;

my @AoA ;

#my $file = "testdata.txt";
#open my ($fh), "<", "$file" or die "$!";
#while  (<$fh>) {
while  (<DATA>) {
  my @line = split ; 
  push @AoA, [@line] ;
}

say for @AoA;   # shows array references
say @{$AoA[0]}[0] ;  # dereference an inner element
foreach my $i (0..$#AoA)
{
 say "@{$AoA[$i]}[2..4]" ; # prints columns 3-5 
} 

dd (@AoA) ;   # dump the data structure we created ... just to look at it.

__DATA__
1 2 3 0 8 8
4 5 6 0 7 8
7 8 9 0 6 7

Upvotes: 2

shawnhcorey
shawnhcorey

Reputation: 3601

Try:

for my $synset ( @synsets ){
    my @words = @$synset;
    print "@words\n";
}

Upvotes: 1

Joni
Joni

Reputation: 111219

You'll need to make a list of references to lists, since Perl doesn't allow lists in a list.

@sentences = ();
...
    # in the loop:
    push @sentences, \@words;

To access individual words you can then do the following:

$word = $sentences[0]->[0];

The arrow can be omitted in this case though.

Upvotes: 0

Related Questions