10 April, 2008

Grep with Perl objects

I was having trouble getting grep to work today. I'm a bit of a perl newbie so still unfamiliar with many of perls basics. Anyway I was trying to loop through a list of objects, get the id of the object and see of that was in another list. Looking through as many tutorals as I could find They all had the same basic example:
    @foo = grep(!/^#/, @bar);    # weed out comments
Or elaborated on the regexp theme. So I wrote the equivalent with a comparison operator instead of a regexp.
    my $temp = grep ($object->{'id'} eq $_, @object_id_list');
No, no, no, no! says the compiler, I don't like this at all! Talking to my colleague revealed one small fact. For regular expressions there is no problem with using
    grep(EXP, @array)
But, if you want to do something more complicated then you must use
    grep {BLOCK} @array
So my line becomes
    my $temp = grep {$object->{'id'} eq $_} @object_id_list';
My biggest bugbear with perl is that sometimes the documentation is not very clear and some more  examples in perldoc would help to clarify a lot of confusion to the perl beginner.