Perl 中的命名参数 [英] Named parameters in Perl

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

问题描述

我正在尝试在 Perl 中使用命名参数.我一直在使用 http://perldesignpatterns.com/?NamedArguments 作为参考.

I'm attempting to use named parameters in Perl. I've been using http://perldesignpatterns.com/?NamedArguments as a reference.

这似乎是有道理的.但是,我似乎无法实际获取发送的值.

It seems to make sense. However, I can't seem to actually get the values sent in.

我也尝试过更改为 $args{'name'}$args{"name"},但没有成功.我似乎无法获得传入的值.我需要查看哪个方向才能弄清楚到底发生了什么?

I have tried changing to $args{'name'}, $args{"name"} as well and no luck. I just can't seem to get the values passed in. Which direction do I need to look in to figure out what on earth is happening?

package doh;
sub new ()
{
   my %args = @_;
   $name = $args{name};
   print $name;
}
1;
__END__

文件 test.pl

use warnings;
use doh;
$trial = doh::;
$trial->new(name => "Tyson");

运行 test.pl 时不打印输出.

No output is printed when test.pl is run.

推荐答案

我不确定你想用 $trial = doh::; 做什么,但你的主要问题是您正在尝试在处理方法调用者之前处理参数.

I'm not sure what you're trying to do with $trial = doh::;, but your main problem is you're trying to process arguments before dealing with your method invocant.

首先,用

use strict;
use warnings;

是的,两者都需要.

在 Perl 中调用方法(与普通子例程相反)时,-> 运算符(invocant)左侧的东西被推到参数列表的开头.所以你需要先把它从清单上去掉.对于构造函数方法,调用者通常是类名.对于实例方法,它将是对象本身.所以

When calling methods in Perl (as opposed to ordinary subroutines) the thing on the left-hand side of the -> operator (the invocant) is pushed onto the beginning of the argument list. So you need to get that off the list first. In the case of your constructor method, the invocant will usually be the class name. For an instance method, it will be the object itself. So

sub new {
    my $class = shift;
    my %args = @_;

    print "name is: $args{name}\n";
}

(如果你不想使用shift,你也可以直接写my ( $class, %args ) = @_; )

(If you don't want to use shift, you could also just write my ( $class, %args ) = @_; )

对于实例方法,约定是命名变量$self.

For instance methods, the convention is to name the variable $self.

还要注意,我已经删除了子程序名称后面的括号;这些对 OO 方法没有任何功能,无论如何它们可能不会按照您的想法行事.

Notice also that I've removed the parens after the subroutine name; these don't have any function for OO methods and they probably don't do what you think, anyway.

这篇关于Perl 中的命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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