perl - "Modification of a read-only value" on while loop with implicit $_ variable -
i don't understand why following piece of perl code
#!/usr/bin/perl -w use strict; use warnings; strange($_) qw(a b c); sub strange { open file, '<', 'some_file.txt' or die; while (<file>) { } # line 10 close file; }
is throwing following error
modification of read-only value attempted @ ./bug.pl line 10.
is bug? or there should know usage of magic/implicit variable $_
?
the while (<fh>)
construct implicitly assigns global variable $_
.
this described in perlop
:
if , if input symbol thing inside conditional of while statement (...), value automatically assigned global variable $_, destroying whatever there previously. (...) $_ variable not implicitly localized. you'll have put local $_; before loop if want happen.
the error thrown because $_
aliased constant value ("a"
).
you can avoid declaring lexical variable:
while (my $line = <file>) { # $line }
Comments
Post a Comment