List::Util::first の返り値でハマったのでメモ

use Test::Base qw(no_plan);
use Test::Exception;
use List::Util qw(first);
use Perl6::Say;

my $arr = [
    { id => 1, name => 'aaa' },
    { id => 2, name => 'bbb' },
];
my $is_ccc = sub { $_->{name} eq 'ccc' };

lives_ok( sub {
    map { say $_->name } first { $is_ccc->($_) } @$arr;
}, 'first' );
# => died: Can't call method "name" on an undefined value at -e line 20.

lives_ok( sub {
    map { say $_->name } grep { $is_ccc->($_) } @$arr;
}, 'grep' );
# => ok.

原因は、
first { $is_ccc->($_) } @$arr;

(undef)
を返すからだと思われる。

podにはこうかかれている。

This function could be implemented using C<reduce> like this
$foo = reduce { defined($a) ? $a : wanted($b) ? $b : undef } undef, @list


ちょっとずつ前にすすんでる気がする!!。