Search code examples
arraysperlmoose

Using List::Util first on an array of Moose objects


I have an array called aTestCaseList which is initialized and filled with (Moose) objects of type "Testcase". As expected I can print out the Attribute TestName of every Testcase Object in aTestCaseList. But when I try to find the first Object in the list named "Test4" using https://perldoc.perl.org/List/Util.html#first I get the following error

Can't call method "TestName" on an undefined value

Why are the objects in the array suddenly undefined?

use Testcase;

my @aTestcaseList=();
for (my $i=1; $i <= 9; $i++) {
  push(@aTestcaseList,Testcase->new("Test".$i));
}
my $sTestcase="Test4";
foreach my $sTestDummy(@aTestcaseList)
{
     #Works as expected and prints: Test1 Test2 Test3 ... Test9
     print $sTestDummy->TestName." "; 
} 
# throws the error:
my $sFindTest=first {$_->TestName eq $sTestcase} @aTestcaseList;

package Testcase;
use Moose;
use namespace::autoclean;

has 'TestName' => (is =>'ro',isa=>'Str');

around BUILDARGS => sub
{
    my $orig = shift;
    my $class = shift;

    if ( @_ == 1 && ! ref $_[0] ) {
        return $class->$orig(TestName => $_[0]);
    }
    else {
        return $class->$orig(@_);
    }
};
__PACKAGE__->meta->make_immutable;
1;

Solution

  • You forgot to import the function first from List::Util like

    use List::Util qw(first);