Perl的地图功能与OO perl

时间:2011-08-23 12:53:39

标签: perl oop

在Perl对象的方法中,我想在变量列表上调用另一个方法。像这样使用地图不起作用:

($open, $high, $low, $close) 
    = map( $self->adjust_for_factor, ($open, $high, $low, $close) );

...

sub adjust_for_factor {
    my $self = shift;
    my $price = shift;

    return $price *  $self->get_factor ;
}

这是有效的,但它的丑陋并且无法扩展。我确信必须可以在这里使用地图:

($open, $high, $low, $close) 
= (  $self->adjust_for_factor($open)
, $self->adjust_for_factor($high)
, $self->adjust_for_factor($low)
, $self->adjust_for_factor($close) );

我想这是以正确的方式引用自我的问题。我无法概念化它们如何组合在一起。

感谢所有花时间考虑/留下反馈的人。

3 个答案:

答案 0 :(得分:7)

正如@tchrist所说,你忘了将$_传递给你的方法。正确的方法是

($open, $high, $low, $close)    
    = map $self->adjust_for_factor($_), $open, $high, $low, $close;

您还可以修改方法,以便它可以接受列表:

sub adjust_for_factor {
    my ($self, @prices) = @_;

    return map $_ * $self->get_factor, @prices;
}

($open, $high, $low, $close)      
     = $self->adjust_for_factor($open, $high, $low, $close);

答案 1 :(得分:4)

您忘记将参数传递给对象的方法(帽子提示),这是一个有效的例子:

$ cat l1.pl
use strict;
package p;

sub new { return bless({factor => $_[1]}, $_[0]); }
sub get_factor { return $_[0]->{factor}; }
sub adjust_for_factor {
    my ($self, $price) = @_;
    return $price * $self->get_factor;
}

package main;

my $obj = p->new(3); # Don't use "self" for object name outside object's class!
my @res = map ($obj->adjust_for_factor($_), qw(1 2 3));
print join(", ", @res) . "\n";

$ ./l1.pl
3, 6, 9

答案 2 :(得分:3)

($open, $high, $low, $close) =
    map $self->adjust_for_factor, $open, $high, $low, $close;

应该是

($open, $high, $low, $close) =
    map $self->adjust_for_factor($_), $open, $high, $low, $close;

可以缩短为

$_ = $self->adjust_for_factor($_)
    for $open, $high, $low, $close;