In my attempts to write more efficient code, i have come up with a few situations where i dont understand exactly what Perl is doing, and thus can't decide which way to code something for faster execution.

Basically i am trying to figure out when a function is called, and then exited, what sticks around for subsequent calls, and what is destroyed and needs to be recreated internally on each call.

# case 1 sub blah { ... my @list = qw(# list of things); foreach my $item (@list) { ... } # case 2 { my @list; BEGIN { @list = qw(# list of things); } sub blah { ... foreach my $item (@list) { ... } } # case 3 sub blah { ... foreach my $item qw(# list of things) { ... }
I'm assuming that @list is not going to ever change in blah().

In case 1, im pretty sure that @list is re-initialized on each call to blah()

In case 2, @list is initialized once, in the BEGIN{}, and never goes away, because of the closure.

case 3, i am not sure what happens. Does the inline list re-create itself on each call to blah(), or is it created once and sticks around somewhere? I'm uncertain about this one because the list is never assigned to a variable (as a whole), which makes me think that its sticking around somewhere.

I could ask similar questions about inlined regexs, etc.

UPDATE:
changed my blah {} to sub blah {} - as it should be.


In reply to Resource allocation question by shemp

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.