How can I create multidimensional arrays in Perl?

I am a bit new to Perl, but here is what I want to do:

my @array2d;
while(<FILE>){
  push(@array2d[$i], $_);
}

It doesn't compile since @array2d[$i] is not an array but a scalar value.

How should I declare @array2d as an array of array?

Of course, I have no idea of how many rows I have.

Answers


To make an array of arrays, or more accurately an array of arrayrefs, try something like this:

my @array = ();
foreach my $i ( 0 .. 10 ) {
  foreach my $j ( 0 .. 10 ) {
    push @{ $array[$i] }, $j;
  }
}

It pushes the value onto a dereferenced arrayref for you. You should be able to access an entry like this:

print $array[3][2];

Need Your Help

Conditionally match, but without extra space

php regex

This regex: http://regexr.com/3a9id matches correctly:

how to repeat last word of a line using notepad++

regex replace find notepad++

I have multiple lines in a file. I want to repeat the last word on a line with additional suffix space or tab and prefixed with ,.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.