I don’t really understand why the following piece of perl code
#!/usr/bin/perl -w
use strict;
use warnings;
strange($_) for qw(a b c);
sub strange {
open FILE, '<', 'some_file.txt' or die;
while (<FILE>) { } # this is line 10
close FILE;
}
Is throwing the following error
Modification of a read-only value attempted at ./bug.pl line 10.
Is this a bug? Or there is something I should know about the usage of the magic/implicit variable $_?
The
while (<fh>)construct implicitly assigns to the global variable$_.This is described in
perlop:The error is thrown because
$_is initially aliased to a constant value ("a").You can avoid this by declaring a lexical variable: