Convert bytes to readable units in Perl

February 6th, 2013
179 words · 1 minutes read · 0 Comments

I recently used code similar to that below in VPSMon, and came across a need where it would be convenient to display bytes as a more human-friendly string in Perl. Basically I’m building a script, and I want to convert the amount of available/free RAM on a machine from bytes to gigabytes for display to a user, but I figured may as well cover all bases and have this around in case it needs to display other units/multiples in the future.

So, with a little bit of tweaking, here it is!

Pass bytes as the first argument, and optionally a ‘truesy’ second argument if you’d rather the multiple of 1000 vs the default 1024.

1
2
3
4
5
6
7
8
9
10
sub bytes_to_human {
my ($bytes, $mul) = @_;
return $bytes . " B" if ($bytes < 1024);
$mul = $mul ? 1000 : 1024;

my $exp = int(log($bytes) / log($mul));
my @pre = qw/ K M G T P E /;
my $pre = $pre[$exp-1] . ( $mul == 1024 ? 'i' : '' );
return sprintf("%.2f %sB", ($bytes / POSIX::pow($mul, $exp)), $pre);
}

Posted in: Tech
Tagged: code, perl
Originally published at: http://texh.net/blog/convert-bytes-to-readable-units-in-perl

Leave a comment