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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.