Quantcast

Perl loop causes strange read-only error

Get the WebProNews Newsletter:


[ Business]

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 $p\n";
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

A.P. Lawrence provides SCO Unix and Linux consulting services http://www.pcunix.com

Perl loop causes strange read-only error
Comments Off
Top Rated White Papers and Resources

Comments are closed.

  • Join for Access to Our Exclusive Web Tools
  • Sidebar Top
  • Sidebar Middle
  • Sign Up For The Free Newsletter
  • Sidebar Bottom