There's more than one way to do things PerlMonks

### Re^3: The Definitive Unit Conversion Script

by Aristotle (Chancellor)
 on Dec 13, 2002 at 19:37 UTC ( #219716=note: print w/replies, xml ) Need Help??

"Definitive" in the sense that it effortlessly converts into all related units, not in the amount of units handled. :)

Of course it would be nice to add some limited parsing and intrinsic "understanding" of units and I can see how I'd go about implementing the basic idea (split into numerator and denominator, convert, divide), but how complex a unit specification should it be able to handle? I don't want to add so much weight that it turns into a small expression evaluator. I'm thinking one unit in the numerator, one in the denominator, and one power given for each sounds like a viably complex, sufficiently flexible spec.

Makeshifts last the longest.

• Comment on Re^3: The Definitive Unit Conversion Script

Replies are listed 'Best First'.
(tye)Re3: The Definitive Unit Conversion Script
by tye (Sage) on Dec 13, 2002 at 20:20 UTC

This doesn't have to be complicated. Split on * and before /, then check for /\^\d+\$/:

```    my @units= split m#(?<=.)(?:(?=/)|\*)#, \$units, -1;
my %power;
for my \$unit (  @units  ) {
my \$power= 1;
if(  \$unit =~ s#\^(\d+)\$##  ) {
\$power= \$1;
}
if(  \$unit =~ s#^/##  ) {
\$power= -\$power;
}
\$power{\$unit} += \$power;
}
# ...
then you have to find units that you can convert to with matching powers. So, if you start with kg/cm/sec [ which becomes (kg=>1,cm=>-1,sec=>-1) ] and are asked to return lb/ft/hr (lb=>1,ft=>-1,hr=>-1), then you have to convert from kg to lb, then convert cm to either ft or hr (there will be no cm-to-hr path so you'll do cm-to-ft), then convert the left-overs, sec-to-hr. And you're done.

(Updated and tested.)

- tye

Create A New User
Node Status?
node history
Node Type: note [id://219716]
help
Chatterbox?
 [Eily]: karlgoethebier: more like grata non persona :P Discipulus personae non gratae.. [Corion]: Your Mother: Hmm - I have the pmdev nodelet, which has some links, but I'm not sure what links/guides there are [Corion]: pmdev wiki maybe? [Discipulus]: uh neat karl! [Your Mother]: Both good things to try, thank you!

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (9)
As of 2017-07-21 08:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
I came, I saw, I ...

Results (319 votes). Check out past polls.