Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

hex (3272)

hex
  (email not shown publicly)
http://downlode.org/

Perl, RDF and wiki hacker, London, UK. This is my former Perl blog; I now write at Earle's Notebook [downlode.org].

Journal of hex (3272)

Thursday April 17, 2008
07:35 AM

A Perl Variable I'd Like

[ #36170 ]
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.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • 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 [cpan.org].

    • Lovely! And not even another hard-to-remember symbol, so even better. I'll look forward to having it around in the core.
    • ...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!
      --
      rjbs