[Bioperl-l] $_ assignment question

Aaron J Mackey ajm6q at virginia.edu
Fri Aug 1 09:06:04 EDT 2003


You got caught by lists vs. arrays:

perl -wle 'for(qw(a b)) { $_ = "b"; print; }'
Modification of a read-only value attempted at -e line 1.

perl -wle '@a = qw(a b); for(@a) { $_ = "b"; print; }'
b
b

So problems with reassigning to $_ that might arise in the second case are
quite silent and insidious.

-Aaron

On Fri, 1 Aug 2003, Dave Howorth wrote:

> Jonathan Barber wrote:
> > On Thu, Jul 31, 2003 at 04:01:51PM -0400, Aaron J Mackey wrote:
> >>Of course, this particular brand of pedanticness would indicate that this
> >>construct:
> >>
> >>while(<FH>) {
> >>  # ...
> >>}
> >>
> >>... should also never be used.
> >
> > Yep. At least not in a module. The reason being if I do this:
> >
> > for (qw(different sequence filehandes)) {
> >     $Bioperl_object->random_method($_); # method assigns to $_
> >     do_something_else_with_fh($_);
> > }
> >
> > then do_something_else() is not getting what I expect it to get.
>
> I was interested by this, so I ran the code (Perl 5.6.1). Turns out it
> won't run. Perl says:
>
>    Modification of a read-only value attempted at Test.pm line 14.
>
> It does this even with warnings and strict OFF. I'd say this was strong
> supporting evidence that Jonathan is right :) It also seems that:
>   (i)  problems of this kind will show up pretty quickly and
>   (ii) they can be isolated by putting:
>
> for ('once') { ... }
>
> around the tests of any (all!) method calls.
>
> Cheers, Dave
>
>
> test.pl
> =======
> #!/usr/bin/perl
>
> use lib ('.');
> use Test;
>
> for (qw(hello world)) {
>   print "\nA $_\n\n";
>   Test::g();
>   print "\nB $_\n";
> }
>
> Test.pm
> =======
> #!/usr/bin/perl
>
> package Test;
>
> require Exporter;
>
> our @ISA       = qw(Exporter);
> our @EXPORT    = qw();
> our $VERSION   = 1.00;
>
> sub g
> {
>   open FH, '<', 'test.pl';
>   while (<FH>) {
>    print $_;
>   }
> }
>
>
>

-- 
 Aaron J Mackey
 Pearson Laboratory
 University of Virginia
 (434) 924-2821
 amackey at virginia.edu




More information about the Bioperl-l mailing list