1. Computing

How to get the size of a file in Perl using file test operators.

By

Perl has a set of useful File Test Operators that can be used to quickly get information about the file system like the existence of a file, or the size. Lets take a quick look at how to get the file size in bytes using File Test Operators.
 #!/usr/bin/perl -w
 
 $filename = '/path/to/your/file.doc';
 $filesize = -s $filename;
 print $filesize; 
Simple enough, right? First you create a string that contains the path to the file that you want to test, then you use the -s File Test Operator on it. You could easily shorten this to one line using simply:
 print -s '/path/to/your/file.doc'; 
Also, keep in mind that this will always return true if a file is larger than zero bytes, but will be false if the file size is zero. It makes a handy and quick way to check for zero byte files.
  1. About.com
  2. Computing
  3. Perl
  4. Programming Perl
  5. File System
  6. Perl file size tutorial - How to get the size of a file in Perl using file test operators.

©2014 About.com. All rights reserved.