In general, if I need to use C-style for loops to traverse arrays, I simply put the @array limit directly in the condition:

for( my $i = 0; $i < @array; ++i ) { ...; }

I realise that you were probably thinking that as you have two nested loops running to the same limit, it might be more efficient to do the size 'calculation' before both and use a scalar; but the reality is that there is no calculation being done, the size of the array represented by @array is simply a direct reference to an internal integer, so the cost is actually less than referencing the integer value of a scalar variable.

The difference isn't big enough to worry about for most purposes:

cmpthese -1,{ a=>q[ my @a = 1 .. 1e3; for( my $i = 0; $i < @a; ++$i ){ for( my$j = 0; $j < @a; ++$j ){ 1; } } ], b=>q[ my @a = 1 .. 1e3; my $l = @a; for( my $i = 0; $i < $l; ++$i ){ for( my $j = 0; $j < $l; ++$j ){ 1; } } ] };; Rate a b a 5.81/s -- -41% b 9.84/s 69% -- [0] Perl>

But the point is that there is little purpose in assigning the size of an array to a scalar variable, just reference it directly when you need it.

Ditto for the length of a perl string.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked

In reply to Re^5: Lagrange Polynomials in Perl by BrowserUk
in thread Lagrange Polynomials in Perl by Mascasc

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.