简体   繁体   中英

perl get reference to temp list returned by function without making a copy?

I have a function in perl that returns a list. It is my understanding that when foo() is assigned to list a copy is made:

sub foo() { return `ping 127.0.0.1` }

my @list = foo();

That @list then needs to be transferred to another list like @oldlist = @list; and another copy is made. So I was thinking can I just make a reference from the returned list like my $listref = \\foo(); and then I can assign that reference, but that doesn't work.

The function I'm working with runs a command that returns a pretty big list (the ping command is just for example purposes) and I have call it often so I want to minimize the copies if possible. what is a good way to deal with that?

Make an anonymous array reference of the list that is returned

my $listref = [ foo() ];

But, can you not return an arrayref to start with? That is better in general, too.


What you attempted "takes a reference of a list" ... what one cannot do in the literal sense; a list stands for a mere collection of scalars in a program , while a reference can be taken (my emphasis)

By using the backslash operator on a variable , subroutine , or value .

and a "list" isn't either (with a subroutine we need syntax \\&sub_name )

However, with the \\ operator a reference is taken, either to each element of the list if in list context

my @ref_of_LIST = \( 1,2,3 );  #-->  @ref_of_LIST: (\1, \2, \3)

or to a scalar if in scalar context, which is what happens in your attempt. Since your sub returns a list of values, they are evaluated by the comma operator and discarded, one by one, until the last one. The reference is then taken of that scalar

my $ref_of_LIST = \( 1,2,3 );  #--> $ref_of_LIST: \3

As it happens, all this applies without parens as well, with \\foo() .


See the last part of this post (and links in it), for example

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