How to get the file size in Perl?
Question
How to get the file size in Perl?
In Perl, getting the size of a file is straightforward using the built-in -s file test operator. This operator returns the size of the file (in bytes) when given a filename or filehandle. It’s one of Perl’s many file test operators, which are very handy for querying the status of files.
Using the -s File Test Operator
The simplest way to get a file's size is:
-s $filenamereturns the size (in bytes) of the file named$filename.- If the file doesn't exist or is inaccessible,
-sreturnsundef, which evaluates as false.
This operator works by taking a scalar (string filename) or filehandle and returning the file size in bytes.
Perl Concepts Involved
- Sigil: The
-soperator starts with a hyphen and is a file test operator. - Context: In scalar context,
-sreturns file size in bytes or undef. - TMTOWTDI: There are multiple ways to get file size (e.g. using
stat), but-sis the simplest for basic use.
Example: Getting File Size with -s
#!/usr/bin/perl
use strict;
use warnings;
my $filename = 'example.txt';
# Check if the file exists first
if (-e $filename) {
# Get file size in bytes
my $size = -s $filename;
# Print the size
print "Size of '$filename' is $size bytes.\n";
} else {
print "File '$filename' does not exist.\n";
}
To test this code, create a file named example.txt in the same directory as the script, then run it via perl scriptname.pl.
Alternative: Using stat()
You can also get file size by calling Perl's stat function, which returns a list of information about the file. The file size is the 8th element (index 7):
my $size = (stat($filename))[7];
This method works well, but -s is often preferred for simplicity and clarity.
Common Pitfalls
- Using
-son a non-existent file returnsundef, so always check file existence with-efirst or handle the undef case. -sworks on files, but may not behave as expected on special files like pipes or directories.- File size is in bytes; if you want kilobytes or megabytes, you'll need to convert accordingly.
In summary, -s is the concise, idiomatic way to get a file size in Perl for most beginner use cases.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 5ms
File 'example.txt' does not exist.
(empty)Was this helpful?
Related Questions
- How to use File::Find to recursively search directories in Perl?
- How to use Path::Tiny for file operations in Perl?
- How to use File::Copy to copy files in Perl?
- How to get file modification time in Perl?
- How to use File::Slurp to read files in Perl?
- How to open a file with specific encoding in Perl?