3

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?

G. Cito
  • 6,210
  • 3
  • 29
  • 42
nish
  • 6,952
  • 18
  • 74
  • 128
  • you can write the C-style `for` loop more idiomatically in Perl as `foreach my $i (0 .. $size -1 )` which is arguably easier to read. (and instead of `$size - 1` you can use `$#synsets` which gives the index of the last item in @synsets) – plusplus Jul 16 '13 at 11:08

3 Answers3

2

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
G. Cito
  • 6,210
  • 3
  • 29
  • 42
  • I claim no authority on their use but I'm finding references and anonymous data strictures (hashes and arrays) so useful I'm now not sure when *not* to use them. They've even started to show up when I write [one liners like this](http://stackoverflow.com/a/17643714/2019415). There are many good guides to using references in `perl` ([and discussions here on SO for example](http://stackoverflow.com/q/17414364/2019415)) - experience and familiarity seem to be deciding factors on when and how to do so. – G. Cito Jul 16 '13 at 15:06
1

Try:

for my $synset ( @synsets ){
    my @words = @$synset;
    print "@words\n";
}
shawnhcorey
  • 3,545
  • 1
  • 15
  • 17
0

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.

Joni
  • 108,737
  • 14
  • 143
  • 193