http://www.perlmonks.org?node_id=80143


in reply to Regex Misuse

More experienced programmers are shaking their heads right now, they know it would be much more efficient to ...

The truly experienced programmer doesn't conflate efficiency with effectiveness, but that's worth a separate discussion.

Using a regex to parse fixed-width fields does indeed sound like overkill, but using substr isn't necessarily the most effective alternative. Splitting a record with multiple fixed-width fields requires multiple calls to substr, along with cascading math to make sure that the substr's start at the right places. Contrast that with a regexp-based solution, which requires a single invocation of a regexp, and no additional bookeeping. And then there's the oft-overlooked unpack.

The psgrep example in The Perl Cookbook demonstrates a method for separating fixed-width fields by constructing a format string for unpack. It also demonstrates an elegant way of documenting how the format string is assembled.