views:

111

answers:

2

Is it possible to assign an array variable to an array reference instead of to scalar variables?

Instead of this:

($a, $b) = some_sub(\@d, \@e);

I want something like this:

(@x, @y) = some_sub(\@x1, \@y1);

If so, how can I dereference it.where as in case of former, @$xxxx does for us.

Thanks.

+3  A: 

A reference is a scalar (by definition), even if what it refers to isn't. So I'm not quite sure what you mean by "assign an array variable to an array reference instead of to scalar variables." You can push array references into normal arrays as members and then dereference them straightforwardly. You can also return references from subroutines.

You could dereference the return value of a subroutine in the assignment. I wonder if this is the kind of thing you are trying to do?

my @array = @{ some_sub() };

Note that as Axeman comments below this isn't itself a good idea or especially necessary. If what you really want is to get the items out of the sub-routine and then into arrays, Depesz's suggestion is the kind of thing you need.

I highly recommend perldoc perlreftut as an introduction to references in Perl. You might also look at perldoc perllol and perldoc perldsc.

It might help if you explain what you're really trying to do and why?

Telemachus
Seems like a workaround for `some_sub` being designed by a Perl newbie. Anybody who passes back a *single* array reference in a list context doesn't know what they are doing in Perl or isn't trying hard enough.
Axeman
@Axeman: it's a fair point. I really wasn't suggesting it, so much as trying to figure out what the OP meant or wanted. I'm editing my answer to clarify that.
Telemachus
What's wrong with passing a single array reference in list context? A list of one item is as good as any other list. You don't always have to return a long list of things just because you have list context: especially if you're array reference points to thousands of things. :)
brian d foy
@Axeman, I tend to be wary of creating subs with special context dependent behavior. For the most part, if I write a sub that returns an array ref in scalar context, it will do so in list context as well.
daotoad
+6  A: 

You can do it in 2 steps (3 lines actually):

my ($x_ref, $y_ref) = some_sub(\@x1, \@y1);
my @x = @{ $x_ref };
my @y = @{ $y_ref };

The question is - wouldn't it be simpler to simply ditch the direct arrays, and start using references everywhere?

depesz
... in which case, you would use $x_ref->[0] to reference the first element, and [] to define a reference, e.g. $x1 = [4, 5]; after which $x1->[0] == 4 and $x1->[1] == 5
Rini