SPUG: Odd read only error in 5.6 but not before?

Matt Tucker tuck at whistlingfish.net
Mon Apr 16 04:01:15 CDT 2001


-- David Dyck <dcd at tc.fluke.com> spake thusly:

> On Sat, 14 Apr 2001, Chris Wilkes wrote:
> 
>> This little program fails with a "modification of read-only
>> variable" error at the while(<FOO>) statement under 5.6 but not under
>> previous versions.
>> 
>> I can modify it to do a "foreach my $letter ..." and then send down
>> "compit($letter)" which then works.
>> 
>> Am I missing something here?
> 
> you can see that the foreach loop is setting $_ to
> each readonly constant "a.txt" and "b.txt", right?
> the while (<FOO>)  loop tries to assign to $_
> 
> The following patch creates a localized copy of $_

What's interesting is that following works:

    use strict;
    for (qw(/tmp/a.txt)) {
        compit($_);
    }

    sub compit {
        my $file = shift;
        open (FOO, $file) || die "Can't read file '$file'\n";
        for (<FOO>) {
            print;
        }
        close FOO;
    }

for (...) does something like:

    *_ = \"a.txt";

Which actually aliases $_ to the value in question. for (...) does this
so that the values being iterated over can by modified within the loop
(if they're not constant, of course).

I would recommend not using $_ in the first loop (it doesn't help
increase readability; it just introduces the likelihood of problems
such as those you're having). Instead do something like:

    for my $file (qw(a.txt b.txt)) {
        compit ($file);
    }

    sub compit {
        my $file = shift;
        open (FOO, $file) || die "Can't read file '$file'\n";
        while (<FOO>) {
            print;
        }
        close FOO;
    }

Although arguably you should still use the local($_) call before the
while loop, just to avoid this sort of thing happening again.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
Url : http://mail.pm.org/archives/spug-list/attachments/20010416/aa68e0f6/attachment.bin


More information about the spug-list mailing list