Mini Shell
#!/usr/bin/perl
# encoding: utf-8
#
# author: Kyle Yetter
#
package IMH::Bytes;
use strict;
use warnings;
require Exporter;
our @ISA = qw(Exporter);
our %EXPORT_TAGS = ( 'all' => [ qw(
byte_format parse_bytes %BYTE_UNIT_PRECISION %BYTE_UNIT_ORDER @BYTE_UNITS
) ] );
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
our @EXPORT = qw( byte_format parse_bytes );
our $VERSION = '0.01';
our @BYTE_UNITS = qw( TB GB MB KB B );
our %BYTE_UNIT_ORDER = ();
foreach ( 0 .. $#BYTE_UNITS ) {
$BYTE_UNIT_ORDER{ $BYTE_UNITS[ $_ ] } = 2 ** ( 10 * ( $#BYTE_UNITS - $_ ) );
}
our %BYTE_UNIT_PRECISION = (
TB => 2, GB => 2, MB => 1,
KB => 0, B => 0
);
sub parse_bytes($) {
my $byte_string = uc( shift );
if ( $byte_string =~ /^\s*(\d+)\s*([TKGM]?B)/ ) {
return ( $1 + 0 ) * $BYTE_UNIT_ORDER{ $2 };
}
return $byte_string + 0;
}
sub byte_format($) {
my $bytes = shift;
my $size = $bytes / ( 1024.0 ** $#BYTE_UNITS );
foreach my $unit ( @BYTE_UNITS ) {
if ( $size >= 1 ) {
my $precision = $BYTE_UNIT_PRECISION{ $unit };
return sprintf( "%.${precision}f %2s", $size, $unit );
}
$size *= 1024;
}
return "$bytes B";
}
1;
Zerion Mini Shell 1.0