go ahead... be a heretic | |
PerlMonks |
Re^2: sub scope questionby papidave (Pilgrim) |
on Feb 07, 2008 at 13:17 UTC ( [id://666788]=note: print w/replies, xml ) | Need Help?? |
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.:
which produces:
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
In Section
Seekers of Perl Wisdom
|
|