|
|
Perl Loop Causes Strange Read-only Error
By A.P. Lawrence
Expert Author
Article Date: 2006-10-24
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
caroomba("first");
@dayval=qw(foo ba);
foreach $dayval (@dayval) {
# no problem here
caroomba($dayval);
}
foreach $dayval ("foo2","ba2") {
# no problem here either
caroomba($dayval);
}
foreach ("foo3","ba3") {
# doesn't like this
$dayval=$_;
caroomba($dayval);
}
sub caroomba {
my $p=shift;
print "Caroomba called $pn";
open(I,"./t");
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 ./t.pl 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 APLawrnece.com
About the Author: A.P. Lawrence provides SCO Unix and Linux consulting services http://www.pcunix.com
|
|