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; }
In reply to Re: mile/kilometer converter (category: stupid regex tricks)
by jryan
in thread mile/kilometer converter (category: stupid regex tricks)
by Your Mother
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |