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! # we're substituting \b(\d+(?:\.\d+)?)\b # find a number \s+ # followed by space (kilometer|mile)s? # "km"s or "m"s ! # 1/2 done sprintf "%.1f %s%s", # convert, $1 * ($2eq'mile'?1.6:.63), # if "m"s, use 1.6 ($2eq'mile'?'kilometer':'mile'), # if "km"s, use .63 ($1*($2eq'mile'?1.6:.63))==1?'':'s' # do the math !xieg; # ignore, execute, repeat print $sentence, "\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: mile/kilometer converter (category: stupid regex tricks)
by jryan (Vicar) on Apr 20, 2003 at 10:32 UTC | |
by Aristotle (Chancellor) on Apr 21, 2003 at 02:41 UTC | |
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 |