Hi monks, I'm fairly new to Perl, and I have a basic question about how foreach loops work. Say you want to iterate through an array, @a, in some particular order, but @a is not yet sorted in that order. Would it be better (i.e., faster) to sort @a beforehand, and then use it in the loop, or is it fine to sort in-line with the loop? Basically, if I don't care about preserving the current order of @a, which of these two methods is preferred:
Method 1:
@a = sort @a;
foreach (@a) { ... }
Method 2:
foreach (sort @a) { ... }
I prefer Method 2 simply because it's slightly less code, but I'm concerned that maybe it's re-sorting @a on each iteration, which would be bad. I notice that the following code runs forever:
my @a = (1);
foreach (@a) { push @a, 1; }
So the loop doesn't fix at its start what it's going to iterate through, which is what makes me think Method 2 might be inefficient. Although maybe the loop decides that it's going to iterate through @a, whatever that may be, whether it changes or not within. So it is fixed in a sense, in which case Method 2 is fine I think, although really now I'm just more confused.
Thanks for any insight into how this actually works.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.