sub human_size { my $val = shift; # 2**10 (binary) multiplier by default my $multiplier = @_ ? shift : 1024; my $magnitude = 0; my @suffixes = qw/B KB MB GB TB PB EB/; my $rval; while (($rval = sprintf("%.2f",$val)) >= $multiplier) { $val /= $multiplier; $magnitude++; } # Use Perl's numeric conversion to remove trailing zeros # in the fraction and the decimal point if unnecessary $rval = 0 + $rval; if(wantarray) { ($rval, $magnitude, $suffixes[$magnitude]); } else { "$rval $suffixes[$magnitude]"; } } ## ## Example code below ## # read value from the command line my $val = shift; # Scalar context example printf "Size: %s\n", scalar human_size($val); # List context example my @fancy_suffixes = map "${_}bytes", '', qw/kilo mega giga tera peta +exa/; my ($hval, $mag, $sfx) = human_size($val, 10**3); $hval .= ' decimal' if $mag; # omit for values < 1KB $hval = "$hval $fancy_suffixes[$mag] ($sfx)"; print "Size: $hval\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: "Human" pretty-printer for data capacity
by andreas1234567 (Vicar) on Oct 03, 2007 at 09:03 UTC | |
|
Re: "Human" pretty-printer for data capacity
by grinder (Bishop) on Oct 03, 2007 at 10:47 UTC | |
by calin (Deacon) on Oct 03, 2007 at 11:52 UTC |