
Untitled
By: a guest on
Apr 20th, 2012 | syntax:
None | size: 0.94 KB | hits: 9 | expires: Never
use strict;
my %PREFIX = (
kilo => 1000,
mega => 1000**2,
giga => 1000**3,
tera => 1000**4,
kibi => 1024,
mebi => 1024**2,
gibi => 1024**3,
tebi => 1024**4,
);
sub convert_hash_bytes {
my ($prefix, $bits_or_bytes, $hashref) = @_;
my $div = 1;
if (defined $prefix) {
die "unknown prefix $prefix" unless $div = $PREFIX{ $prefix };
}
die "second arg to convert_hash_bytes must be bits or bytes"
unless $bits_or_bytes =~ /\A(?:bits|bytes)\z/;
my $mul = $bits_or_bytes eq 'bits' ? 8 : 1;
return if $mul == 1 and $div == 1;
for my $key (grep { /_bytes$/ } keys %$hashref) {
my $value = delete $hashref->{ $key };
$hashref->{ $key } = int($value * $mul / $div);
}
return;
}
my $hashref = {
foo => 10,
bar => 20,
ugga_bytes => 3810123192,
ooga_bytes => 38291,
};
use Data::Dumper;
convert_hash_bytes(mebi => bytes => $hashref);
print Dumper($hashref);