Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 20th, 2012  |  syntax: None  |  size: 0.94 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. use strict;
  2.  
  3. my %PREFIX = (
  4.   kilo => 1000,
  5.   mega => 1000**2,
  6.   giga => 1000**3,
  7.   tera => 1000**4,
  8.  
  9.   kibi => 1024,
  10.   mebi => 1024**2,
  11.   gibi => 1024**3,
  12.   tebi => 1024**4,
  13. );
  14.  
  15. sub convert_hash_bytes {
  16.   my ($prefix, $bits_or_bytes, $hashref) = @_;
  17.  
  18.   my $div = 1;
  19.   if (defined $prefix) {
  20.     die "unknown prefix $prefix" unless $div = $PREFIX{ $prefix };
  21.   }
  22.  
  23.   die "second arg to convert_hash_bytes must be bits or bytes"
  24.     unless $bits_or_bytes =~ /\A(?:bits|bytes)\z/;
  25.  
  26.   my $mul = $bits_or_bytes eq 'bits' ? 8 : 1;
  27.  
  28.   return if $mul == 1 and $div == 1;
  29.  
  30.   for my $key (grep { /_bytes$/ } keys %$hashref) {
  31.     my $value = delete $hashref->{ $key };
  32.     $hashref->{ $key } = int($value * $mul / $div);
  33.   }
  34.  
  35.   return;
  36. }
  37.  
  38.  
  39. my $hashref = {
  40.   foo => 10,
  41.   bar => 20,
  42.   ugga_bytes => 3810123192,
  43.   ooga_bytes => 38291,
  44. };
  45.  
  46. use Data::Dumper;
  47. convert_hash_bytes(mebi => bytes => $hashref);
  48. print Dumper($hashref);