On 18/08/2014 09:17, Ken Peng wrote:

sub myfunc {
   my @x=(1,2,3);
   return \@x;
}

# or,

sub myfunc {
   my @x=(1,2,3);
   return [@x];
}

which one is the better way to return the list content? And if the
method is an instance method?

The first version of the subroutine is the best choice in the code shown
because it is less wasteful and has no external effect. It simply
creates an array, populates it, and returns a reference to that array.

The second option creates the same array and populates it, but then
copies it to another anonymous array, deletes the first array, and
returns a reference to the copy.

The big difference that is being missed so far is that, if the array was
static in some way, then returning a reference to it is very different
from returning a reference to a copy.

Consider this, where array @xx continues to exist and keeps its values
across calls to either subroutine

    my @xx = ( 1, 2, 3 );

    sub mysub1 {
      \@xx;
    }

    sub mysub2 {
      [ @xx ];
    }

Now mysub1 will supply a reference to @xx itself, while mysub2 gives a
reference to a snapshot of @xx at the time of the call. Which of these
is best depends entirely on your purpose.

None of this seems relevant to your question about an instance method,
which in general will reflect the current state of the object. If you
explain the behaviour of the object better than we can help you more.

HTH,

Rob




---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to