in reply to returning ref to static var vs. copying

The construct [ @list ] creates a new array reference, into which @list is expanded (i.e. copied), so that's bloat.

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

    But that's deprecated.

    It was never deprecated since it was never valid.

      The warning message Perl itself emits when it encounters this construct describes it as "deprecated". Surely it's reasonable to follow that example?

        Of deprecation, Wikipedia says

        In computer software standards and documentation, the term deprecation is applied to software features that are superseded and should be avoided.

        ok, so I guess it is deprecated. (It was born that way.)