在map {}内调用对象的方法的语法

时间:2016-01-20 00:22:08

标签: perl

这行代码my %web_events = map { $_->[1]->epoch } @events;

抛出此错误:

Can't call method "epoch" without a package or object reference

$_->[1]Time::Piece对象,我正在尝试调用epoch方法。

这里的语法是什么?

更新

my @events = ();
push (@events, [ 'Blah', Time::Piece->new() ]);
my %web_events = map { $_->[1]->epoch => 1 } @events;

更新2 @events数据

$VAR23 = [
           'John Manzi',
           bless( [
                    50,
                    48,
                    2,
                    28,
                    1,
                    '116',
                    0,
                    58,
                    0,
                    1456645730,
                    1
                  ], 'Time::Piece' ),
           bless( [
                    50,
                    48,
                    5,
                    28,
                    1,
                    '116',
                    0,
                    58,
                    0,
                    1456656530,
                    1
                  ], 'Time::Piece' )
         ];
$VAR24 = [
           'Christopher John',
           bless( [
                    50,
                    48,
                    0,
                    29,
                    1,
                    '116',
                    1,
                    59,
                    0,
                    1456724930,
                    1
                  ], 'Time::Piece' ),
           bless( [
                    50,
                    48,
                    3,
                    29,
                    1,
                    '116',
                    1,
                    59,
                    0,
                    1456735730,
                    1
                  ], 'Time::Piece' )
         ];

更新3

好的,我越来越近,似乎我将对象存储在匿名数组中的方式是错误的。这里有一些代码可以更好地反映我的内容:

my $t = Time::Piece->new();
my $start = $t + 3600; 
my @events = ();
push (@events, [ 'Blah', $start ]);
my %web_events = map { $_->[1]->epoch => 1 } @events;

1 个答案:

答案 0 :(得分:4)

  

$_->[1]是一个Time :: Piece对象,我试图调用epoch   方法。

你确定吗?

您的数据必须如此,才能成为现实:

use strict;
use warnings;

use Data::Dump;
use Time::Piece;

my @events = (
    [0, Time::Piece->new],
    [1, Time::Piece->new],
    [2, Time::Piece->new],
    # ...
);

my @epochs = map { $_->[1]->epoch } @events;
dd(\@epochs);

输出:

[1453249703, 1453249703, 1453249703]

由于该代码显然工作正常,我猜你有数据问题,而不是语法问题。

此外,将map的结果分配到散列中可能不是您想要的,因为它会产生一个散列,其中键和值是相同的" thing"。此外,如果您的阵列具有奇数个元素,您将收到以下警告:

  

哈希分配中奇数个元素...

要查找" one of these things that's not like the other",您可以:

print Dumper([grep { ref($_->[1]) ne 'Time::Piece' } @events])