this question succeeds the following question: Moose: Array of Objects->loop through Attribute I'm struggling to implement the grep syntax into a List::Compare Object:
my @aIdentList=("z003","t302","p032");
my $lc=List::Compare->new('-u',\@aIdentList,\@{(grep {$_->Identifier}@aArray1)});
my @unique=$lc->get_unique;
\@{(grep {$_->Identifier}@aArray1)}
This part is weird. You are trying to dereference a list via @{}
. That doesn't work.
The grep
returns a list already. You do not need to use parenthesis ()
to construct a new list. Perl will ignore them. Then your @{}
is simply wrong. You need a new array reference. That's []
. It will construct a new array ref from the list that grep
returns. That's already enough to pass to List::Compare->new
. The backslash \
is only needed if you want to take a reference of something, but you now already have a reference.
But you actually do not want to grep
here. You want to map
!
This is what your code should look like.
List::Compare->new( '-u', \@aIdentList, [ map { $_->Identifier } @aArray1 ] )
grep
will filter out every element of the list you pass in where the block does not return a true value. Since all objects in @aArray1
(typing this is horrible!) have an Identifier
property, this will let all elements through. The second array ref arg to new
will then be a list of objects. That's not what you want, because you'd be comparing apples to oranges.
Instead, you need to use map
, which will pass the return value of the block for each element. It's like an inline foreach
loop. Then your second list will be the actual identifiers of the objects, and not the objects themselves.