martes, 7 de julio de 2009

perl arrays and subs. returning arrays of arrays

Now a bit of perl I've been fiddling at $work.

We know that perl flattens lists when passed as arguments to functions (subs) or when we want to return more than one element in a sub. Today I spent 10 minutes remembering how all that worked (c++ is doing nasty things in my brain).

We have some options to avoid the flattening.

sub a { @a = (1,2,1); @b = (4,3,4); [\@a ,\@b]} a; #return a reference (scalar) to an array of arrayrefs.
> [[1,2,1],[4,3,4]]
sub a { @a = (1,2,1); @b = (4,3,4); (\@a ,\@b)} a; # return a list of two references to arrays. returns the last element by default. see below to access other elems
> [4,3,4]
sub a { @a = (1,2,1); @b = (4,3,4); (\@a ,\@b)} (a)[0]; #Same, just accessing other elements
> [1,2,1]
sub a { @a = (1,2,1); @b = (4,3,4); [@a ,@b]} a; # returning a reference to an array containing the two arrays flattened into one list.
> [1,2,1,4,3,4]

I like the first option because you can manage all the info in the most flexible way.
Otherwise, if you want to do multiple assignations when returning, you can use the second way like this:
sub a { @a = (1,2,1); @b = (4,3,4); (\@a ,\@b)}
my ($arr_ref1, $arr_ref2) = a;

And that's it. not really enlightening, but hey, I'm still learning my way to perl :p

No hay comentarios: