1

I've seen other questions about making two dimensional arrays, but most of these seem to be dealing with a lot of array variables within array variables. I'm having trouble following them. What I want to do is take this:

my @array = [ [50, 1], [52, 2], [45, 3], [60, 4] ];

And be able to reference it and print it out as a two dimensional array (I'm using this script to generate an html file.) But whenever I try to reference the length of @array, it comes out as 1. What is the right syntax for printing this array, or referencing either a pair of coordinates or an individual number?

For example, how would I reference the sub-array [50, 1] vs referencing the "1" element?

Charles Goodwin
  • 6,402
  • 3
  • 34
  • 63
user2933738
  • 75
  • 1
  • 1
  • 9

2 Answers2

3

The outermost brackets [] should be parentheses (). Square brackets [] gives you an array reference, which you need to have inside the array, because nested elements must be references in perl.

So:

my @array = ([50, 1], [52, 2], [45, 3], [60, 4]);
print length(@array); # Should give 4.

# Iterate & print
foreach my $sub_array (@array) {
    print "a: $sub_array->[0], b: $sub_array->[1]\n";
} 
mwarin
  • 75
  • 7
  • So, the code for iterating over each of these would be something like: foreach my @subarray (@array) { foreach my $element (@subarray) { print $element; } } ? – user2933738 Mar 11 '14 at 18:33
  • 2
    The basic idea is that an array can't contain other arrays. They have to be array references. So when you loop through your array of array references you need to de-reference them. Check out the perl reference tutorial (perlreftut) at perldoc: http://perldoc.perl.org/perlreftut.html – mwarin Mar 11 '14 at 18:42
1

You can do it like this:

#!/usr/bin/perl
use strict;
use warnings;

my @array = ( [50, 1], [52, 2], [45, 3], [60, 4] );

print join(" ", @array) . "\n"; #prints all array references (not very useful)

print join(" ", @{$array[1]}) . "\n"; # prints 52 2

print ${$array[0]}[1] . "\n"; # prints 1

I explained it in more detailed here

Here's an example of how to iterate through it:

for my $arr_ref (@array) {

  for my $element ( @{$arr_ref} ) {
    print $element . ", "; 
  }
  print "\n";
}

Output:

50, 1, 
52, 2, 
45, 3, 
60, 4, 
Community
  • 1
  • 1
hmatt1
  • 4,939
  • 3
  • 30
  • 51