Kredler Stefan wrote:
>
> Hi all,
Hello,
> 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?
I don't know about elegant but I know you can make it a lot shorter.
> 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 (@_);
@_ is the default argument for shift() in subroutines so:
my $unit = shift;
> my $last = "";
> return $unit if (not ($unit =~ /\d/));
return $unit unless $unit =~ /\d/;
> while ( substr($unit,length($unit)-1,1) =~ /\D/ ){
> $last = substr($unit,length($unit)-1,1);
> substr($unit,length($unit)-1,1) = ""; #truncate
> }
$last = substr $unit, -1, 1, '' while $unit =~ /\D$/;
> 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;
> }
> }
if ( $last =~ /G/ ) { $unit *= 1E9 }
elsif ( $last =~ /M/ ) { $unit *= 1E6 }
elsif ( $last =~ /[kK]/ ) { $unit *= 1E3 }
elsif ( $last =~ /m/ ) { $unit *= 1E-3 }
elsif ( $last =~ /u/ ) { $unit *= 1E-6 }
elsif ( $last =~ /n/ ) { $unit *= 1E-9 }
elsif ( $last =~ /p/ ) { $unit *= 1E-12 }
> 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";
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]