Stupid Perl tricks: kilometer/mile converter

[I realize most of you probably want a working example or code you could use more easily online, so—JavaScript utility: kilometer/mile converter.]

use strict;
my $sentence = ( join " ", @ARGV ) ||
    "Give me a sentence containing kilometers or miles or both.\n" .
    '   Eg: "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.609:.6214),   # if "m"s, use 1.6
        ($2eq'mile'?'kilometer':'mile'), # if "km"s, use .63
        ($1*($2eq'mile'?1.6:.63))==1?    # do the math
                               '':'s'    # add "s" if appropriate
        !xeg;                           # ignore \s, exec, repeat

print $sentence, "\n";
Give me a sentence containing miles or kilometers or both.
   Eg: "I live 9.7 kilometers from here."
jinx~>kilo-mile A marathon is 27 miles long.
A marathon is 43.4 kilometers long.
digg stumbleupon reddit Fark Technorati Faves