in reply to Re (2): Hash/Array of Regular Expressions? (code)
in thread Hash/Array of Regular Expressions?

Good question. I agree that sometimes map obscures things. However, I find it obscuring when it's used in void context (instead of a foreach loop). However, I also find that using a foreach loop where a mapping is happening obscures things.

I used map because:<bl>

  • I assumed that the patterns weren't necessarily going to be in the program text (ruling out your literal
    @array = ( qr{^abcd}, qr{cd[ef]g}, qr{cat$} );
    option)
  • To me, the operation reads more clearly this way: I'm transforming an array of strings into an array of regexes by applying an operation to each of them. This is communicated most clearly (IMO) by the map operator. My problem with the foreach is that it tends to obscure the meaning of the code. We see a loop, then we have to decode it to figure out that it is in fact doing the same thing as a map. Kent Beck would call using map intention revealing.
  • I mostly use Smalltalk, where this is the idiomatic way to do it. </bl> In Smalltalk, this operation would be written as:
    regexes := strings collect: [ :ea | Regex new: ea ].
    In Smalltalk, every collection responds to the collect: message, which passes each of the elements of the collecion into a block (equivalent to a Perl CODE ref) whose output is collected into a collection of the same species as the original collection. So Perl's map operator corresponds directly to Smalltalk's collect: methods.

    Also, Perl's grep operator corresponds directly to Smalltalk's select: methods.

    update: changed title because of topic change