1

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;
0

1 Answer 1

4

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

use List::Util qw(first);
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, you are right. I think I did misinterpret the error message. I thought for some reason the objects itself are undefined.
Without a declaration for first, first {$_->TestName eq $sTestcase} @aTestcaseList was interpreted as the (do {$_->TestName eq $sTestcase})->first(@aTestcaseList) indirect method call. $_ is undefined, so $_->TestName threw that error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.