Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the size of a file in megabytes using Perl?

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.

like image 969
cowgod Avatar asked Feb 04 '09 15:02

cowgod


People also ask

How do I check the size of a file in Perl?

my $size = (stat $filename)[7];

How do I check the size of a file in MB?

You can retrieve the length of the file with File#length(), which will return a value in bytes, so you need to divide this by 1024*1024 to get its value in mb.

How do you measure file size?

File sizes are measured in Bytes (B), Kilobytes (KB), Megabytes (MB), Gigabytes (GB), Terabytes (TB) and so on. The file sizes can be measured using a binary system (where kilo means 1024) or metric system (kilo means 1000).


1 Answers

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
like image 53
jrockway Avatar answered Oct 13 '22 02:10

jrockway