Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Why use map here? (re: Hash/Array of Regular Expressions?)

by bikeNomad (Priest)
on Jun 24, 2001 at 20:19 UTC ( [id://91073]=note: print w/replies, xml ) Need Help??


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

  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Domain Nodelet?
    Node Status?
    node history
    Node Type: note [id://91073]
    help
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this?Last hourOther CB clients
    Other Users?
    Others lurking in the Monastery: (2)
    As of 2024-04-25 07:46 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found