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.
my $size = (stat $filename)[7];
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With