Google Groups Home
Help | Sign in
Message from discussion How to pass around an Array of Arrays (or Array Refs)
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
jerrykrin...@gmail.com  
View profile
 More options May 13, 10:56 am
Newsgroups: comp.lang.perl.misc
From: jerrykrin...@gmail.com
Date: Tue, 13 May 2008 07:56:39 -0700 (PDT)
Local: Tues, May 13 2008 10:56 am
Subject: How to pass around an Array of Arrays (or Array Refs)
I need to pass an array of arrays from a function, but I can't make an
array of arrays work.  Actually, I've got better results making an
array of array references.  Here's what I've done:

#!/usr/bin/perl

my @array ;
my @row ;
@row = ('a00', 'a01') ;
push (@array, \@row) ;
@row = ('a10', 'a11') ;
push (@array, \@row) ;
@row = ('a20', 'a21') ;
push (@array, \@row) ;

# In real life I will return @array to the caller, but the
# problem can be demonstrated without doing that...

my $nRows = @array ;
foreach my $array_ref (@array) {
    # $array_ref is a reference to an array (row)
    # Dereference it.
    my @row = @$array_ref ;
    # Print each element (column) separated by spaces
    foreach my $element (@row) {
        print "$element    ";
    }
    # Next row, new line
    print "\n" ;

}

My expected result is:

    a00    a01
    a10    a11
    a20    a21

but the actual result is:

    a20    a21
    a20    a21
    a20    a21

What am I doing wrong?

Thanks,

Jerry Krinock


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.

Create a group - Google Groups - Google Home - Terms of Service - Privacy Policy
©2008 Google