perlmeditation
ase
I thought I'd share an enlightenment I had recently with the community, hoping someone else can have a similar breakthrough. Until now, I've always shied away from <code>map</code> and <code>grep</code>. I understood how they worked (on the surface) but never seemed to find a situation where they "fit". I didn't fully understand their power. It was like having a tool in my toolbox without taking it out of the wrapper.
<p>The other day I was playing around with a two little OO modules, I'll call one <code>Item</code> and one <code>Collection</code> for sake of argument.
<p><code>Item</code> has two main attributes: <br>
<code>VAL</code> :a scalar value. and<br>
<code>USABLE</code> :a flag that denotes the items availability.<p>
<code>Collection</code> is just that: a collection of <code>Item</code> objects with added methods to do stuff with the collections. It's main attribute is <code>ITEMS</code> which is a referance to an array of Item objects.
<p>Now that I've set the scene and bored half the audience to tears I come to the problem that led to enlightenment.
I wanted a method in <code>Collection</code> to return a scalar that was a concatenation of the values (sorted numerically) of all the objects in the collection whose <code>USABLE</code> flag was true. I ended up with this:<br>
<code>
#method in Collection object
stringify {
my $self = shift;
return join("",sort {$a <=> $b}
map {$_->{VAL}}
grep {$_->{USABLE}} @$self->{ITEMS});
}
</code>
<p>
The great part is, once I wrote it, it seemed 'natural'. It just fit. I used to read this kind of code and go "uhhhh, Ok that's cool but I'll never write something like that let alone be able to decipher it". I feel I've crossed some sort of learning plateau, or passed an important rite of passage.<br>
That's it.. on to the next level<br>
-[ase]