R – How to handle optional parameters in Moose


I'm currently starting with Perl OOP using the "Moose" package.

The compiler complains that it "Can't modify non-lvalue subroutine call at Parser.pm line 16."

I don't quite understand why I can't just assign a new object. I guess there is a better or more valid way to do optional parameters with Moose?

    #!/usr/bin/perl -w

package Parser;

use Moose;

require URLSpan;

require WWW::Mechanize;

has 'urlspan' => (is => 'rw', isa => 'URLSpan', required => 1);
has 'mech' => (is => 'rw', isa => 'WWW::Mechanize');

sub BUILD {
    my $self = shift;
    if(!$self->mech) {
        warn("no Mech set for " . $self->urlspan->name);
        $self->mech = WWW::Mechanize->new(agent => 'Mozilla/5.0 (Windows; U; Windows NT 6.0; de; rv: Gecko/2009011913 Firefox/3.0.4',
                                         stack_depth => 1
                                         ); #line 16


Best Solution

$self->mech is a method call; you can't really treat it like a field in a C struct. If you want to set it, you need to pass the new object to it.

                agent => 'xyz',
                stack_depth => 1