Perl stat - How to get the size of a file

Perl FAQ: How do I determine the size of a file from within a Perl program/script?

Solution -  the Perl stat function

Just use the Perl stat function to get the file size. Here is a quick example.

Example - get the file size with Perl stat

To determine size of a file named foo.txt, just use a little Perl code like this:

$filename = 'foo.txt';
# use the perl stat function, and get the file size field
$filesize = (stat($filename))[7];
print "filesize = $filesize\n";

Note that you really want to be sure that file exists before checking the filesize. You test to see if a file exists with Perl like this:

$filename = '';
if (-e $filename) {
  print "the file exists\n";
} else {
  print "the file does not exist!\n";