SPUG: Readable, well-written code (was: Best One-Liners and Scripts
for UNIX)
Jeremy Kahn
kahn at cpan.org
Sun Apr 20 14:06:04 CDT 2003
Brian Hatch wrote:
>>Grep has more cohesion than a loop because its function is limited
>>to selecting members from a list.
>>
>>
>Well, not always:
>
> grep { s/(\d+)/ $1 * 2 /e } @list;
>
>That'll take the first string of numbers in each element of @list
>(perhaps lines from a file) and double the number. It's actually
>modifying @list, not just selecting members.
>
>Is more readable than the following?
>
> for ( @list ) {
> s/(\d+)/ $1 * 2 /e;
> }
>
>Well, the grep one is cleaner to me - less lines to read.
>
My take on this is that just because you *can* use 'grep' in place of
'for' doesn't mean you *should*.
If the goal is to put it on one line, do this:
for (@list) { s/(\d+)/ $1 * 2/e }; # semicolon because it clarifies
that I think of this as 1 statement
If the goal is to put the list on the right, use the wacky
postconditions that Tim hates (you can leave the
braces out if you like):
{ s/(\d+)/ $1 * 2/e } for (@list);
>Others may dissagree, and I wouldn't include it when teaching someone for the
>first time how to do that.
>
>
IMO, grep should really be reserved for searching through a list and
picking out certain elements. The "side effect" of changing the list is
black magic that is unexpected and scary.
My $0.02,
Jeremy
More information about the spug-list
mailing list