views:

86

answers:

4

Can anyone please tell me how to dereference an array of arrays when passed to a function. I am doing like this:

my @a={\@array1, \@array2, \@array3};

func(\@a);


func{  
@b=@_;

@c=@{@b};  
}

Actually I want the array @c should contain the addresses of @array1, @array2, and @array3.

A: 

Should be

func {
    $b = shift;
}

if you're passing in a reference. Hope that helps some.

Mark C
+4  A: 
my @a={\@array1, \@array2, \@array3};

Is an array with a single member-> a hash containing

{ ''.\@array1 => \@array2, ''.\@array3 => undef }

Because as a key in the hash, Perl coerces the reference to @array1 into a string. And perl allows a scalar hash reference to be assigned to an array, because it is "understood" that you want an array with the first element being the scalar you assigned to it.

You create an array of arrays, like so:

my @a = ( \@array1, \@array2, \@array3 );

And then in your function you would unpack them, like so:

sub func {
    my $ref = shift;
    foreach my $arr ( @$ref ) { 
        my @list_of_values = @$arr;
    }
}

or some variation thereof, like say a map would be the easiest expression

my @list_of_entries = map { @$_ } @$ref;

In your example, @c as a list of addresses is simply the same thing as a properly constructed @a.

Axeman
A: 

Read the perlreftut documentation.

Edit: Others point out a good point I missed at first. In the initialization of @a, you probably meant either @a = (...) (create array containing references) or $arrayref = [...] (create reference to array), not {...} (create reference to hash). The rest of this post pretends you had the @a = (...) version.

Since you pass one argument (a reference to @a) to func, @_ is a list containing that one reference. You can get that reference and then dereference it by doing:

sub func {
  my $arrayref = shift;
  my @c = @{$arrayref};
}

Or in one line, it would look like:

sub func {
  my @c = @{shift()};
}

(If you hadn't used the backslash in func(\@a), @_ would be equal to @a, the array of three references.)

aschepler
+5  A: 

You may want to read perldoc perlreftut, perldoc perlref, and perldoc perldsc You can say:

sub func {
    my $arrayref = shift;

    for my $aref (@$arrayref) {
        print join(", ", @$aref), "\n";
    }
}

my @array1 = (1, 2, 3);
my @array2 = (4, 5, 6);
my @array3 = (7, 8, 9);

my @a = \(@array1, @array2, @array3);

func \@a;

or more compactly:

sub func {
    my $arrayref = shift;

    for my $aref (@$arrayref) {
        print join(", ", @$aref), "\n";
    }
}

func [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
Chas. Owens
hi thanks a lot... it worked well.. thank u so much
jack