这是一个老问题,已经得到了正确的回答,但以防你的程序受限于核心模块并且你不能使用Number::Bytes::Human 这里你有几个其他的选项我已经收集了一段时间。我保留它们也是因为每个都使用不同的 Perl 方法,并且是 TIMTOWTDI 的一个很好的例子:
- 示例 1:使用 state 避免每次都重新初始化变量(在 perl 5.16 之前您需要使用 feature state 或 perl -E)
http://kba49.wordpress.com/2013/02/17/format-file-sizes-human-readable-in-perl/
sub formatSize {
my $size = shift;
my $exp = 0;
state $units = [qw(B KB MB GB TB PB)];
for (@$units) {
last if $size < 1024;
$size /= 1024;
$exp++;
}
return wantarray ? ($size, $units->[$exp]) : sprintf("%.2f %s", $size, $units->[$exp]);
}
.
sub scaledbytes {
# http://www.perlmonks.org/?node_id=378580
(sort { length $a <=> length $b
} map { sprintf '%.3g%s', $_[0]/1024**$_->[1], $_->[0]
}[" bytes"=>0]
,[KB=>1]
,[MB=>2]
,[GB=>3]
,[TB=>4]
,[PB=>5]
,[EB=>6]
)[0]
}
- 示例 3:利用 1 Gb = 1024 Mb、1 Mb = 1024 Kb 和 1024 = 2 ** 10 的事实:
.
# http://www.perlmonks.org/?node_id=378544
my $kb = 1024 * 1024; # set to 1 Gb
my $mb = $kb >> 10;
my $gb = $mb >> 10;
print "$kb kb = $mb mb = $gb gb\n";
__END__
1048576 kb = 1024 mb = 1 gb
- 示例4:使用
++$n and ... until ..获取数组的索引
.
# http://www.perlmonks.org/?node_id=378542
#! perl -slw
use strict;
sub scaleIt {
my( $size, $n ) =( shift, 0 );
++$n and $size /= 1024 until $size < 1024;
return sprintf "%.2f %s",
$size, ( qw[ bytes KB MB GB ] )[ $n ];
}
my $size = -s $ARGV[ 0 ];
print "$ARGV[ 0 ]: ", scaleIt $size;
即使您不能使用 Number::Bytes::Human,也请查看源代码以了解您需要注意的所有事项。