SPUG: Readable, well-written code (was: Best One-Liners and Scripts for UNIX)

Brian Hatch spug at ifokr.org
Sat Apr 19 20:54:23 CDT 2003



> My view is that fluent Perl takes advantage of the Perl idioms that enhance
> cohesion and readability and avoids Perl idioms that obfuscate for the sake
> of producing terse code.  An example of this is the grep function.  Any code
> that uses grep can be rewritten more verbosely as a foreach loop.  However,
> grep enhances readability because when the reader sees grep he knows the
> code is selecting members from a list, whereas the loop is less immediately
> obvious.  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.  Others may
dissagree, and I wouldn't include it when teaching someone for the
first time how to do that.



--
Brian Hatch                  "I'm thinking .. pastels!"
   Systems and
   Security Engineer
http://www.ifokr.org/bri/

Every message PGP signed
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.pm.org/pipermail/spug-list/attachments/20030419/b6f5f200/attachment.bin


More information about the spug-list mailing list