如何处理Moose中的可选参数? [英] How do I handle optional parameters in Moose?

查看:150
本文介绍了如何处理Moose中的可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用"Moose"软件包开始Perl OOP.

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

编译器抱怨它无法在Parser.pm第16行修改非左值子例程调用."

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

我不太明白为什么我不能只分配一个新对象.我猜想有一种更好或更有效的方法来用Moose做可选参数吗?

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:1.9.0.6) Gecko/2009011913 Firefox/3.0.4',
                                         stack_depth => 1
                                         ); #line 16
        }

}

推荐答案

$self->mech是方法调用;您不能真正将其像C结构中的字段一样对待.如果要设置它,则需要将新对象传递给它.

$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.

        $self->mech( 
            WWW::Mechanize->new(
                agent => 'xyz',
                stack_depth => 1
            )
        );

这篇关于如何处理Moose中的可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆