使用对象方法的 Perl 映射

标签 perl map-function instance-method

我有一个 Perl 模块文件 MyClass.pm,其中包含一个非常基本的类定义。

use strict;
use warnings;

package MyClass;

sub new {
    my $this = shift;
    my $self = {};
    bless $self, $this;
    return $self;
}

sub displayChar{
    my $self = shift;
    my $char = shift;
    print $char . "\n";
}

1;

我还有一个 myClass.pl 文件,用于创建 MyClass 的实例。

#!/usr/bin/perl
use strict;
use warnings;

use MyClass; 
my $myClass = MyClass->new();

$myClass->displayChar('a'); # This line works right

my @charArray = ('a', 'b', 'c');
map($myClass->displayChar, @charArray);

当我调用 displayChar 方法时,它工作正常,但是当我尝试将 map 函数与该方法一起使用时,它给我这个错误三次(我猜每个数组项一次):

Use of uninitialized value $char in concatenation (.) or string at MyClass.pm line 16.

我是否以错误的方式使用 map 功能?或者也许无法使用对象方法作为第一个参数?

最佳答案

您需要将一个值传递给您的 displayChar 方法:

map($myClass->displayChar($_), @charArray);

map在本地将 $_ 变量设置为数组的每个值。

关于使用对象方法的 Perl 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40383445/

相关文章:

perl - Perl 5.8 与 5.10 和 5.12 的子例程中的代码延迟评估有什么区别?

linux - stty : standard input: Inappropriate ioctl for device

c++ - "map"函数式编程函数的 STL 名称

javascript - 数组上的 .map() 迭代器函数传递了什么?

python - 在 Python 中为实例方法添加属性

python - 树数据结构中的根节点操作

perl - 无法安装 Date::Manip perl 模块。不断收到 cpanmetadb 错误

regex - 继续在 perl 中换行

ruby - 将实例方法委托(delegate)给类方法