Perl loop causes strange read-only error

    October 24, 2006

Ok, folks: I don’t understand this. It must have something to do with anonymous arrays in Perl (no, it doesn’t, I realize now), but I don’t grok the connection.

I ran into this in attempting a seemingly simple change in some customer’s code; it wasn’t hard to fix, but I simply do not understand why this happened.

Well, that’s not precisely true: it happened because I went ahead in a hurry and added something “quick”. It was just a new loop around some existing code. Ordinarily I would have written it like this:

@foo=qw(foo ba);
foreach $loopvar (@foo) { ..

But for some reason I did this instead:

#!/usr/bin/perl -w
# no problem here

@dayval=qw(foo ba);
foreach $dayval (@dayval) {
# no problem here

foreach $dayval ("foo2","ba2") {
# no problem here either

foreach ("foo3","ba3") {
# doesn't like this

sub caroomba {
my $p=shift;
print "Caroomba called $p\n";
while (<I>) {
# stuff..
close I;

When run, that produces:

Caroomba called first
Caroomba called foo
Caroomba called ba
Caroomba called foo2
Caroomba called ba2
Caroomba called foo3 Modification of a read-only value attempted at ./ line 23, <I> line 23.

Why? Dude, werent you listening? I do not comprehend why. Some person with more brains than I currently have will have to explain that one to both of us.

*Originally published at

A.P. Lawrence provides SCO Unix and Linux consulting services