http://www.perlmonks.org?node_id=666788


in reply to Re: sub scope question
in thread sub scope question

I have to admit, I was entirely perplexed as well by this until I realized that my in Perl acts like an actual executed statement, not merely a declaration (like it would be, for example, in C). As a result, you get a new instance of $list_ref every time the function is called -- which is why it doesn't stay shared.

When I want to create a shared variable with long-term state like that (i.e., a C-style "static"), I put the applicable function definitions in a scope block with the my statement at the outer level -- e.g.:

#!/usr/bin/perl -w use strict; my @firstlist = qw(1 2 3 4 5); my @secondlist = qw(A B C D E); process_list(\@firstlist); process_list(\@secondlist); { my $list_ref; sub process_list { ($list_ref) = @_; sub get_list { return @$list_ref; } print_list(); } } sub print_list { foreach my $item (get_list()) { print "LIST ITEM: $item\n"; } }

which produces:

LIST ITEM: 1 LIST ITEM: 2 LIST ITEM: 3 LIST ITEM: 4 LIST ITEM: 5 LIST ITEM: A LIST ITEM: B LIST ITEM: C LIST ITEM: D LIST ITEM: E

as expected. Naturally, you could (per ikegami, should) also move the get_list() subroutine outside the scope of process_list() for clarity, since it doesn't really add value there -- but I left it as-is to minimize changes from your original program.

Update: Strengthened some wording in response to comments from ikegami on Perl internals