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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|