Skip to content

Instantly share code, notes, and snippets.

@dbcooper
Created February 5, 2013 22:13
Show Gist options
  • Select an option

  • Save dbcooper/4718222 to your computer and use it in GitHub Desktop.

Select an option

Save dbcooper/4718222 to your computer and use it in GitHub Desktop.
A confusing bit of code. YMMV.
# A few things have been renamed in an attempt to protect the innocent (and guilty)
package SomePackage;
use SomePackage;
sub LoadUnits {
return if $ser{'m'};
my($file) = "$SomePackage::HOME/etc/serunits.conf";
open(SERUNITS,"<$file") || return;
local ($_); # So we don't clobber our caller's $_
while (<SERUNITS>) {
/^\s*#/ && next; /^\s*$/ && next;
chop;
my($a,$t,$x,$p,$n,$s) = split(':',$_);
my($m,$o,$u) = $x=~/^([-+]?\d*\.?\d*)?([-+]\d*\.?\d*)?\s*(.*)\s*$/;
$ser{$a} = $_;
$serm{$a} = ($serm{$u}||1)*($m || 1);
$sero{$a} = $o * $serm{$u} + $sero{$u};
foreach (split(/[,\s]+/,$s)) { $_ && ($unittab{"$_ $t"}=$a); }
}
close(SERUNITS);
}
sub Conv {
my($f,$t,@v) = @_;
unless ($ser{'m'}) { LoadUnits(); }
my($fm,$fo,$fa) = $f=~/^([-+]?\d*\.?\d*)?([-+]\d*\.?\d*)?\s*(.*)\s*$/;
my($tm,$to,$ta) = $t=~/^([-+]?\d*\.?\d*)?([-+]\d*\.?\d*)?\s*(.*)\s*$/;
$tm=$tm||1; $fm=$fm||1;
$ser{$fa} || return;
my($fd,$ft,$fx,$fp,$fn,$fs,$ff) = split(':',$ser{$fa});
my(%f) = SomePackage::URLDecode($ff);
$ta = $f{$ta} if $f{$ta};
if (!$ser{$ta}) { $ta = $unittab{"$t $ft"}; }
my($td,$tt,$tx,$tp,$tn,$ts,$tf) = split(':',$ser{$ta} || $ser{$fa});
my($mult,$offs) = (1,0);
if ($ser{$ta} && $ft eq $tt && $fa ne $ta) {
$mult=$serm{$fa}/$serm{$ta};
$offs=($sero{$fa}-$sero{$ta})/$serm{$ta};
}
$offs = $to + ($offs-$fo*$mult)/$tm; $mult *= $fm/$tm;
@f{qw(fabbr tabbr type mult offs fname fsrc tname tprec)} =
($fa,$ta || $fx,$ft,$mult,$offs,$fn,$fs,$tn,$tp);
foreach(@v) {
/^\s*$/ && (push @{$f{'v'}},'NA') && next;
if (($fm,$fo,$fa) = /^([-+]?\d*\.?\d*)([-+]\d*\.?\d*)?\s*(.+)\s*$/) {
($fd,$ft,$fx,$fp,$fn,$fs,$fw,$ff) = split(':',$ser{$fa});
if ($ft eq $tt) {
push @{$f{'v'}}, $fm*$serm{$fa}/$serm{$ta} +
($sero{$fa}-$sero{$ta})/$serm{$ta} + $fo;
next;
}
}
push @{$f{'v'}}, (/^\s*[+-]?\.?\d/) ? $_ * $mult + $offs : $_;
}
@{$f{'fv'}} = map { sprintf("%.*f", $f{tprec}, $_) } @{$f{'v'}};
(wantarray && @v!=1) ? %f : $f{'v'}[0];
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment