| 1 |
#!/usr/bin/perl |
| 2 |
use Getopt::Long; |
| 3 |
use File::Basename qw(basename); |
| 4 |
use Math::Calc::Units qw(convert readable calc); |
| 5 |
|
| 6 |
use strict; |
| 7 |
use warnings; |
| 8 |
|
| 9 |
sub usage { |
| 10 |
my ($msg, $bad) = @_; |
| 11 |
my $out = $bad ? *STDERR : *STDOUT; |
| 12 |
|
| 13 |
my $CMD = basename($0); |
| 14 |
if ($msg) { |
| 15 |
print $out "$CMD: $msg\n"; |
| 16 |
} |
| 17 |
|
| 18 |
print $out <<"END"; |
| 19 |
usage: |
| 20 |
|
| 21 |
Calculate the given expression, and guess human-readable units for the result: |
| 22 |
$CMD [-v] [-a] <expr> |
| 23 |
|
| 24 |
Convert the given expression to the requested units: |
| 25 |
$CMD -c <expr> <unit> |
| 26 |
$CMD --convert <expr> <unit> |
| 27 |
|
| 28 |
Examples: |
| 29 |
How long does it take to download 10MB over a 384 kilobit/sec connection? |
| 30 |
$CMD "10MB / 384Kbps" |
| 31 |
|
| 32 |
What is the expected I/O rate for 8KB reads on a disk that reads at 20MB/sec |
| 33 |
and has an average seek time of 15ms? |
| 34 |
$CMD "8KB / (8KB/(20MB/sec) + 15ms)" |
| 35 |
|
| 36 |
Or if you prefer to calculate that by figuring out the number of seconds |
| 37 |
per byte and inverting: |
| 38 |
$CMD "((1sec/20MB) + 15ms/8KB) ** -1" |
| 39 |
|
| 40 |
How many gigabytes can you transfer in a week at 2MB/sec? |
| 41 |
$CMD -c "2MB/sec" "GB/week" |
| 42 |
|
| 43 |
How many angels fit on the heads of 17 pins (with some assumptions)? |
| 44 |
(This demonstrates that unknown units are allowed, with plurals.) |
| 45 |
$CMD "42 angels/pinhead * 17 pinheads" |
| 46 |
END |
| 47 |
|
| 48 |
exit($bad ? 1 : 0); |
| 49 |
} |
| 50 |
|
| 51 |
my $verbose = 0; |
| 52 |
my $abbreviate = 0; |
| 53 |
my $action = 'readable'; |
| 54 |
|
| 55 |
GetOptions("verbose|v!" => \$verbose, |
| 56 |
"abbreviate|abbrev|a" => \$abbreviate, |
| 57 |
"convert|c!" => sub { $action = 'convert' }, |
| 58 |
"help|h!" => sub { usage("", 0) }, |
| 59 |
) |
| 60 |
or usage("invalid arguments", 1); |
| 61 |
|
| 62 |
if ($action eq 'convert') { |
| 63 |
usage("not enough args", 1) if (@ARGV < 2); |
| 64 |
usage("too many args", 1) if (@ARGV > 2); |
| 65 |
my ($expr, $units) = @ARGV; |
| 66 |
if ($units =~ /^\s*\d+/) { |
| 67 |
warn("WARNING: Destination units in conversion should probably not have a value\n"); |
| 68 |
} |
| 69 |
print convert($expr, $units), "\n"; |
| 70 |
} elsif ($action eq 'readable') { |
| 71 |
usage("", 0) if @ARGV == 0; |
| 72 |
usage("too many ARGV", 1) if (@ARGV > 1); |
| 73 |
print "$_\n" foreach readable($ARGV[0], verbose => $verbose, abbreviate => $abbreviate); |
| 74 |
} |
| 75 |
|
| 76 |
1; |