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 use a block expression then you must use
    grep {BLOCK} @array
So my line becomes
    my $temp = grep {$object->{'id'}eq$_} @object_id_list';
I know perl is a very revered language amongst it regular users, but little things like this are very frustrating and not clearly explained in the documentation. Sometimes more elaborate examples in perldoc would help to clarify a lot of confusion to the perl beginner.

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home