Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In Perl prior to 5.10, you can say</p> <pre><code>#!/usr/bin/perl use strict; use warnings; my @a = qw/a b c d e/; my $index; for my $elem (@a) { print "At index ", $index++, ", I saw $elem\n"; } #or for my $index (0 .. $#a) { print "At index $index I saw $a[$elem]\n"; } </code></pre> <p>In Perl 5.10, you use <a href="http://perldoc.perl.org/functions/state.html" rel="noreferrer">state</a> to declare a variable that never gets reinitialized (unlike ones create with <a href="http://perldoc.perl.org/functions/my.html" rel="noreferrer">my</a>). This lets you keep the <code>$index</code> variable in a smaller scope, but can lead to bugs (if you enter the loop a second time it will still have the last value):</p> <pre><code>#!/usr/bin/perl use 5.010; use strict; use warnings; my @a = qw/a b c d e/; for my $elem (@a) { state $index; say "At index ", $index++, ", I saw $elem"; } </code></pre> <p>In Perl 5.12 you can say</p> <pre><code>#!/usr/bin/perl use 5.012; #this enables strict use warnings; my @a = qw/a b c d e/; while (my ($index, $elem) = each @a) { say "At index $index I saw $elem"; } </code></pre> <p>But be warned: you there are <a href="http://perldoc.perl.org/functions/each.html" rel="noreferrer">restrictions</a> to what you are allowed to do with <code>@a</code> while iterating over it with <code>each</code>.</p> <p>It won't help you now, but in Perl 6 you will be able to say</p> <pre><code>#!/usr/bin/perl6 my @a = &lt;a b c d e&gt;; for @a Z 0 .. Inf -&gt; $elem, $index { say "at index $index, I saw $elem" } </code></pre> <p>The <code>Z</code> operator zips the two lists together (i.e. it takes one element from the first list, then one element from the second, then one element from the first, and so on). The second list is a <a href="http://en.wikipedia.org/wiki/Lazy_evaluation" rel="noreferrer">lazy</a> list that contains every integer from 0 to infinity (at least theoretically). The <code>-&gt; $elem, $index</code> says that we are taking two values at a time from the result of the zip. The rest should look normal to you (unless you are not familiar with the <a href="http://perldoc.perl.org/functions/say.html" rel="noreferrer"><code>say</code></a> function from 5.10 yet).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload