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 = 'tempfile.pl';
if (-e $filename) {
  print "the file exists\n";
} else {
  print "the file does not exist!\n";
}

 

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.