Well, if you put the my inside, you set the my, write the variable, run the code, than clean the variable to recreate it in the next loop. If you put outside, you create it only 1 time, than only write to the variable, and this use less CPU.
Depends — oftentimes I need the variable to be undefined at the start of the loop. In that case, I would have to do
my $var; while( $foo ) { # ... undef $var; }
Also, I try to scope very tightly for reasons beyond memory reuse — if you declare a variable inside a block, it's obvious that it's meant strictly for use inside that block. That would be
{ my $var; while( $foo ) { # ... } }

Both workarounds are kludgy and make the code harder to read — and easy to read code is my #2 priority. Efficiency is only my #3 or #4 priority — unless I really need the speed, and have profiled and benchmarked my code and identified the piece of code in question as the hotspot. (#1 is correctly working code, if you were wondering.)

This does not of course affect advice such as smart ordering of conditions as that only rarely makes a difference with readability.

Makeshifts last the longest.


In reply to Re: How Perl Optimize your code & some code TIPS ;-P by Aristotle
in thread How Perl Optimize your code & some code TIPS ;-P by gmpassos

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.