简体   繁体   中英

How can I assign the result of a subroutine call to array references in Perl?

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.

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM