in reply to returning ref to static var vs. copying
Are there any potentially adverse consequences of holding on to references to static variables?
No, since the my @list isn't static. That container will be empty at each subroutine invocation, and it's contents will live in a brand new reference which you can take with \@list...
use strict; use warnings; sub foo { my @list if 0; print "list: (@list)\n"; push @list, @_; \@list; } my $ref1 = foo(1..3); push @$ref1, 'a', 'b'; my $ref2 = foo(4..6); print "first ref: (@$ref1)\n"; print "last list: (@$ref2)\n"; __END__ list: () list: () first ref: (1 2 3 a b) final list: (4 5 6)
...except if you play tricks to the compiler (allocate a private @list on the scratchpad, but don't generate the opcode to clear that list) like so:
use strict; use warnings; sub foo { my @list if 0; print "list: (@list)\n"; push @list, @_; \@list; } my $ref1 = foo(1..3); push @$ref1, 'a', 'b'; my $ref2 = foo(4..6); print "first ref: (@$ref1)\n"; print "final list: (@$ref2)\n"; __END__ list: () list: (1 2 3 a b) first ref: (1 2 3 a b 4 5 6) last list: (1 2 3 a b 4 5 6)
But that's deprecated. For statics (previous perl 5.10) you'd use a block around the sub
use strict; use warnings; { my @list; sub foo { print "list: (@list)\n"; push @list, @_; \@list; } } my $ref1 = foo(1..3); push @$ref1, 'a', 'b'; my $ref2 = foo(4..6); print "first ref: (@$ref1)\n"; print "final list: (@$ref2)\n";
which produces the same output like the infamous 'my if 0' hack above, but you get at a glance what is going on: the @list is allocated in the same scope into which sub foo has been compiled, but @list isn't re-initialized inside the sub.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: returning ref to static var vs. copying
by ikegami (Patriarch) on Jun 10, 2009 at 15:17 UTC | |
by Porculus (Hermit) on Jun 10, 2009 at 22:13 UTC | |
by ikegami (Patriarch) on Jun 11, 2009 at 06:37 UTC |