~~David~~ has asked for the wisdom of the Perl Monks concerning the following question:

I have a method modifier like so:
before 'wafer' => sub{ my $self = shift; if ( ! $self->_wafer_parse_complete ){ $self->_wafer_parse }; };
The _wafer_parse sub has a while loop in it. If I call $obj->wafer( '01' ) a single time, all is well. If I call $obj->wafer( '05' ) a second time with a new value, I get this error:
Use of uninitialized value in subroutine entry at Class/MOP/Method/Wra +pped.pm line 47 Can't use string ("") as a subroutine ref while "strict refs" in use a +t Class/MOP/Method/Wrapped.pm line 47.
I have found that by changing the while loop to a foreach loop, the problem goes away. I am using the while loop to read through a file, so I don't want to use foreach.
Has anyone else had this problem or know of how to fix this? I am using Moose 0.65 and ActiveState Perl 5.10.0. I tried Google search and supersearch, but I couldn't find anything.
Thanks, David

Update1:
one of the strange things, is that _wafer_parse is only ever called for the first instance becuase it sets the _wafer_parse_complete sub to a true value. Just having the while loop in the sub causes this to die, not actually running the sub twice.

Update2:
The method _wafer_parse is something like this. This fails:
sub _wafer_parse { my $self = shift; open my $FILE, "<", $self->{file}; while ( <$FILE> ){}; close $FILE; }
If I removed the open command, the subroutine runs fine.

Replies are listed 'Best First'.
Re: While Loop in Before Modifier Gives Error
by morgon (Priest) on Jun 23, 2009 at 23:27 UTC
    I have posted a Moose-problem the other day and was told to upgrade to a more recent version (evidently 0.82 is current). I have not yet done so, but maybe you want to consider it.

    Apart from that, please post the (stripped down if possible) code of the methods you call to get a better understanding of your problem.

      Thanks... I updated my post. Unfortunately, I already tried to update Moose, but I am having issues with the new version because I can't get the right Name.dll for Sub::Name ( which is a dependency ). It is a long story, but for now, I think I am stuck on Moose 0.65...
Re: While Loop in Before Modifier Gives Error
by ikegami (Patriarch) on Jun 24, 2009 at 16:05 UTC
    It's got nothing to with while or with Moose. _wafer_parse is clobbering its caller's $_. Don't assign to a global variable without localising it first.
    sub _wafer_parse { my $self = shift; open my $FILE, "<", $self->{file}; local *_; while ( <$FILE> ) { ... } }

    Better yet, don't assign to global variables.

    sub _wafer_parse { my $self = shift; open my $FILE, "<", $self->{file}; while ( my $line = <$FILE> ) { ... } }
      Thank you very much. That solved my problem.