Hi all,

a while ago I wrote a little unit conversion I am quite happy with. Just out
of interest: is there a more elegant way to do it? And maybe even more
interesting: what approach should I take to implement the back conversion?

Here is my code:  

#! /usr/gnu/bin/perl -w

##################################################         
#      unit conversion
#      here I loose the SI-Unit like Volt Ampere etc. but I don't need it.
#
sub expand_unit($){
  my $unit = shift (@_);
  my $last = "";
  return $unit if (not ($unit =~ /\d/));
  while ( substr($unit,length($unit)-1,1)  =~ /\D/  ){
    $last = substr($unit,length($unit)-1,1);
    substr($unit,length($unit)-1,1) = ""; #truncate
  }
 SWITCH: {
    if ($last =~ /G/){
      $unit *= 1E9;
      last SWITCH;
    }
    if ($last =~ /M/){
      $unit *= 1E6;
      last SWITCH;
    }
    if ($last =~ /[kK]/){
      $unit *= 1E3;
      last SWITCH;
    }
    if ($last =~ /m/){
      $unit *= 1E-3;
      last SWITCH;
    }
    if ($last =~ /u/){
      $unit *= 1E-6;
      last SWITCH;
    }
    if ($last =~ /n/){
      $unit *= 1E-9;
      last SWITCH;
    }
    if ($last =~ /p/){
      $unit *= 1E-12;
      last SWITCH;
    }
  }
  return $unit;
}


##############################
# some example

$value = "852.52mv"; 

$new_value = expand_unit($value);

#do some calculus with this new_value like: new_value1 - new_value2 ....

print "$value = $new_value\n";

___
   Stefan
   

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to