How do I get the size of a file?
This is very simple.
$filesize = -s $filename;
How do I display filesizes in a nice way?
Below is a basic sub routine that will take the number of bytes as input and return a string with a formatted file size e.g. 29800 bytes becomes "29 kB".
print niceSize($filesize); # prints the formatted filesize
print niceSize($filesize,2); # same as above but prints 2 decimal places
sub niceSize {
# Will work up to considerable file sizes!
my $fs = $_[0]; # First variable is the size in bytes
my $dp = $_[1]; # Number of decimal places required
my @units = ('bytes','kB','MB','GB','TB','PB','EB','ZB','YB');
my $u = 0;
$dp = ($dp > 0) ? 10**$dp : 1;
while($fs > 1024){
$fs /= 1024;
$u++;
}
if($units[$u]){ return (int($fs*$dp)/$dp)." ".$units[$u]; } else{ return int($size); }
}