in reply to mile/kilometer converter (category: stupid regex tricks)
That's no good. Your code is *way* too thick; a simple regex like that shouldn't really be worth commenting with such detail, but because your code is so condensed, they're necessary. And, whenever comments are needed with so short a snippet, its time to take a step back and wonder why.
When you need to perform a complex substitution, you should consider factoring out the code into a simple subroutine. It works wonders for readability; for instance, your example no longer needs comments, as the code is simple enough to explain itself.
my $sentence = ( join " ", @ARGV ) || "Give me a sentence containing kilometers or miles or both.\n" . qq| Eg (note quotes): "I live 6 miles from here."|; $sentence =~ s/\b (\d+(?:\.\d+)?) \s+ (kilometer|mile)/ transform($1,$ +2) /xige; print $sentence, "\n"; sub transform($$) { my ($amnt, $type) = @_; my ($switched, $to, $one) = ($amnt * 0.63, 'mile'); if ($type eq 'mile') { $switched = $amnt * 1.6; $to = 'kilometer'; } $one = 's' if $amnt == 1; sprintf "%.1f %s%s", $switched, $to, $one; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: mile/kilometer converter (why the protoype?)
by Aristotle (Chancellor) on Apr 21, 2003 at 02:41 UTC | |
|
"Point, not, point, not, point, watch the beat!"
by Your Mother (Archbishop) on Apr 21, 2003 at 02:55 UTC | |
by Anonymous Monk on Apr 21, 2003 at 03:14 UTC | |
by jryan (Vicar) on Apr 21, 2003 at 06:31 UTC |