> i haven't run it but i already see conflicts with nested $_. 

It's not obvious that the $_ nesting is a problem.  The point should be moot
because the C<while> loop *should* localize $_.  It doesn't.  Well, it does,
but there's a loophole.

Quoting pg 18 of the 3rd Edition Camel (emphasis added):

    [...]
    while (<STDIN>) { print; }  # the shortest way
    [...]

    When you're implicitly assigning to $_ in a $_ loop, this is the
    *global* variable by that name, not the one localized to the while
    loop.
  
It continues,
    You can protect an existing value of $_ this way:
        while (local $_ = <STDIN>) { print; }  # use local $_


This use of the *global* $_ along with Rafael's description of constants in
a C<..> gives this error line:

    Modification of a read-only value attempted at peter_scott.pl line

Here's a modified version that exercises the bug or eliminates it...


#! /usr/bin/perl

use warnings;
use diagnostics;

my $exercise_bug = 1;           # Set 'true' to show the bug.

for (1..2) {
  print_file($0);
}

for (qw(one two)) {
  print_file($0);
}

sub print_file {
  local @ARGV = shift;
  if ($exercise_bug) {
      # Modification of a read-only value attempted at peter_scott.pl line
20
      while (<>) { print }
  }
  else {
      while (local $_ = <>) { print }
  }
}

Reply via email to