#!/usr/bin/perl use strict; my @firstlist = qw(1 2 3 4 5); my @secondlist = qw(A B C D E); process_list(\@firstlist); process_list(\@secondlist); sub process_list { my($list_ref) = @_; sub get_list { return @$list_ref; } print_list(); } sub print_list { foreach my $item (get_list()) { print "LIST ITEM: $item\n"; } }
Output:
LIST ITEM: 1 LIST ITEM: 2 LIST ITEM: 3 LIST ITEM: 4 LIST ITEM: 5 LIST ITEM: 1 LIST ITEM: 2 LIST ITEM: 3 LIST ITEM: 4 LIST ITEM: 5
Why does the closure "get_list" not get updated to use the reference to @secondlist? I'm assuming there is a scope issue with the way "get_list" is declared. I understand there is a better way to write this with the use of a function that returns an anonymous sub but I'm not sure how to explain the issue with the code above. Better solution:
#!/usr/bin/perl 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 $get_list_sub; sub make_list_closure { my ($ref) = @_; return sub { return @$ref; }; } sub process_list { my($list_ref) = @_; $get_list_sub = make_list_closure($list_ref); print_list(); } sub print_list { foreach my $item ($get_list_sub->()) { print "LIST ITEM: $item\n"; } }

In reply to sub scope question by perl45036

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.