Perl - 无法调用新方法 [英] Perl - Can't Call new Method

查看:58
本文介绍了Perl - 无法调用新方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在做一个小项目,我决定尝试使用 Method::Signatures 因为我觉得它更整洁.

I have been working on a small project and I decided to try and use Method::Signatures because I find it neater.

这是不使用 Method::Signatures 并且它有效,我可以使用包和调用方法.

This is without using Method::Signatures and it works, I'm able to use the package and call methods.

sub new {
    my $self = {};
    bless($self);
    shift;
    $self->{parent} = shift;
    return $self;
}

但是当我尝试这个时,它不起作用:

But when I try this, it doesn't work:

 method new($parent) {
   bless {}, $self;
   $self->{parent} = $parent;
   return $self;
 }

我收到一条错误消息:在使用严格引用时,不能使用字符串(PackageName")作为 hashref".

I get an error saying: "Can't use string ("PackageName") as hashref while strict refs in use".

推荐答案

Method::Signatures 自动将第一个参数移出参数列表并将其放入 $self 中.当你调用像 $obj->foo 这样的对象方法时,$self 就是 $obj.但是当你调用像Class->method这样的类方法时,$self将是字符串Class.

Method::Signatures automatically shifts the first argument off the argument list and puts it in $self for you. When you call an object method like $obj->foo, then $self is just $obj. But when you call a class method like Class->method, then $self will be the string Class.

您的 $self 包含字符串 PackageName,因为您使用 new 作为类方法,所以它应该如此.然后你使用 PackageName 作为 bless 的参数,但是 丢弃结果!

Your $self contains the string PackageName, as it should since you're using new as a class method. Then you use PackageName as an argument to bless, but throw away the result!

bless {}, $self;

这会将一个新的空哈希引用({ })添加到包含在 $self 中的包名称中,然后将结果丢弃.然后,当它只是一个字符串时,您尝试将 $self 用作 hashref,这会导致错误.所以试试这个:

This blesses a new empty hashref (the { } ) into the package name contained in $self and then throws the result away. You're then trying to use $self as a hashref when it's just a string, which is causing the error. So try this:

method new($parent) {
   my $obj = bless {}, $self;
   $obj->{parent} = $parent;
   return $obj;
}

这篇关于Perl - 无法调用新方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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