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.
1) You don't want 1024. That gives you kilobytes. You want 1024*1024, or 1048576.
2) Why would dividing by a magic number be a bad idea? It's not like the number of bytes in a megabyte will ever change. Don't overthink things too much.
You could of course create a function for calculating this. That is a better solution than creating constants in this instance.
No need for constants. Changing the
1024
to some kind of variable/constant won't make this code more readable.I would read this into a variable rather than use a magic number. Even if magic numbers are not going to change, like the number of bytes in a megabyte, using a well named constant is a good practice because it makes your code more readable. It makes it immediately apparent to everybody else what your intention is.
Since the -s operator returns the file size in bytes you should probably be doing something like
and use int() if you need a round figure. It's not like the dimensions of KB or MB is going to change anytime in the near future :)
This is an old question and has been already correctly answered, but just in case your program is constrained to the core modules and you can not use Number::Bytes::Human here you have several other options I have been collected over time. I have kept them also because each one use a different Perl approach and is a nice example for TIMTOWTDI:
http://kba49.wordpress.com/2013/02/17/format-file-sizes-human-readable-in-perl/
.
.
++$n and ... until ..
to obtain an index for the array.
Even if you can not use Number::Bytes::Human, take a look at the source code to see all the things that you need to be aware of.