Perlfunc: human_size()

Quicky function to get data size in human readable format.

sub human_size {
   my $size = shift();

   if ($size > 1024**3) {
      $size = sprintf("%.1fG",$size / 1024**3);
   } elsif ($size > 1024**2) {
      $size = sprintf("%.1fM",$size / 1024**2);
   } elsif ($size > 1024) {
      $size = sprintf("%.1fK",$size / 1024);
   } elsif ($size > 1) {
      $size = sprintf("%dB",$size);
   }

   return $size;
}
Leave A Reply - 1 Reply
Replies
David Edwards 2006-11-30 09:10am - dave@kidindustries.net - Logged IP: 65.115.220.76

I've done similar, I ended up doing all the things manually though, such as inputting 1048576 to the code instead of multiplication. I'm sure the compiler/interpreter can take care of it just fine either way though. ;)

All content licensed under the Creative Commons License