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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.