I've been caught out in the past by expecting to be able to rely on changes to the loop variable being preserved once the loop has terminated. For example, perhaps you want to know at which iteration a
foreach loop terminated early using a
last. However, the loop variable is localised inside the loop so that it reverts to it's old value after the loop.
$ perl -Mstrict -Mwarnings -le '
> my $x = 0;
> print $x;
> for $x ( 1 .. 10 )
> {
> my $y = rand;
> print qq{$x -- $y};
> last if $y > 0.85;
> }
> print $x;'
0
1 -- 0.820319728766666
2 -- 0.070987764836417
3 -- 0.632845876776752
4 -- 0.195428179899814
5 -- 0.847997411282524
6 -- 0.353572570937089
7 -- 0.865375393672675
0
$
You have to preserve the loop variable from inside the loop if you need to access it afterwards.
Cheers,
JohnGG
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.