Named parameters in Perl

北慕城南 提交于 2019-12-13 14:11:46

问题


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.

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?

File doh.pm

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

File test.pl

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

No output is printed when test.pl is run.


回答1:


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.

First, start every Perl file with

use strict;
use warnings;

Yes, you need both.

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";
}

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

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

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.



来源:https://stackoverflow.com/questions/12962461/named-parameters-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!