如何使用Perl以兆字节为单位获取文件的大小? [英] How do I get the size of a file in megabytes using Perl?
本文介绍了如何使用Perl以兆字节为单位获取文件的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
-s
运算符以字节为单位给出了我的大小,但是我将假设然后将其除以一个幻数是一个坏主意: my $ size_in_mb =(-s $ fh)/(1024 * 1024);
我应该只使用一个只读变量来定义1024,还是有编程的方式来获得字节数以千字节为单位?
编辑:更新了不正确的计算结果。
解决方案
如果你想避免幻数,试试CPAN模块。
使用Number :: Bytes :: Human QW(format_bytes);
my $ size = format_bytes(-s $ file); #4.5M
I want to get the size of a file on disk in megabytes. Using the -s
operator gives me the size in bytes, but I'm going to assume that then dividing this by a magic number is a bad idea:
my $size_in_mb = (-s $fh) / (1024 * 1024);
Should I just use a read-only variable to define 1024 or is there a programmatic way to obtain the amount of bytes in a kilobyte?
EDIT: Updated the incorrect calculation.
解决方案
If you'd like to avoid magic numbers, try the CPAN module Number::Bytes::Human.
use Number::Bytes::Human qw(format_bytes);
my $size = format_bytes(-s $file); # 4.5M
这篇关于如何使用Perl以兆字节为单位获取文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文