[ABE.pm] perl 5.10 rules! - lexical topic

Ricardo SIGNES rjbs-perl-abe at lists.manxome.org
Sat Jun 30 17:07:38 PDT 2007


What?  Topic?  Yeah, you know, the "it" variable: $_

Maybe you've never been bitten by this problem, but it stinks:

  for (@data) {
    next if /^#/;
    next if -d;
    s/a/b/;
    sanity_check;
    print;
  }

...see the problem?  Of course not!  It's invisible.  See, sanity_check,
defined far away, assigns to $_.  Since $_ is global, it clobbers what you had
in @data, not to mention that it prints the wrong thing.  The proper behavior
would have been for sanity_check to local-ize $_, but you can't fix it, because
you don't control Sanity::Checker.

Because of this hard-to-predict bug, some people would prefer you always write:

  for my $datum (@data) {
    next if $datum =~ /^#/;
    next if -d $datum;
    $datum =~ s/a/b/;
    sanity_check;
    print $datu;
  }

...but that's like fifty more characters, and a bunch more syntax.  If you
could change your $_ to use a /lexical/ scope, its value would only be set in
the current block, and other blocks would keep on using the global $_.  You'd
write that as:

  for my $_ (@data) {
    next if /^#/;
    next if -d;
    s/a/b/;
    sanity_check;
    print;
  }

In 5.10, this works.

-- 
rjbs


More information about the ABE-pm mailing list