I often find myself doing things with arrays like this:
for (0 .. $#foo) { if ($foo[$_] =~ /corge/) { $bar{$_} = $foo[$_]; } }Simple enough. But consider that if you're reading through a filehandle, you can use $. (or $INPUT_LINE_NUMBER) to tell you how many lines you've read. It'd be very handy to have another special variable - let's call it $ì because there are hardly any symbols left - that, if you're in a loop, gives you the number of times it has run. That way you could replace the code above with:
foreach (@foo) { if (/corge/) { $bar{$ì} = $_; } }This immediately strikes me as Perlish.
Addendum: Well, it would, if use.perl's code formatter didn't buggily replace ì with ¬ in the code snippet above. I hope you can still see what I mean.
5.12 will support each
on arrays. So that would be:
while (my ($num, $line) = each @foo) {
if ($line =~/corge/) {
$bar{$num} = $line;
}
}
You can have this right now with Aaron Crane's Array::Each::Override.
Re:each @array in 5.12
hex on 2008-04-17T13:49:45
Lovely! And not even another hard-to-remember symbol, so even better. I'll look forward to having it around in the core.Re:each @array in 5.12
rjbs on 2008-04-17T13:50:06
...and really, that's much better, because otherwise you'd have to constantly copy $ into a lexical for nested loop. Too much vertical space taken!