file-io beginner

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 $filename returns the size (in bytes) of the file named $filename.
  • If the file doesn't exist or is inaccessible, -s returns undef, 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 -s operator starts with a hyphen and is a file test operator.
  • Context: In scalar context, -s returns file size in bytes or undef.
  • TMTOWTDI: There are multiple ways to get file size (e.g. using stat), but -s is 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 -s on a non-existent file returns undef, so always check file existence with -e first or handle the undef case.
  • -s works 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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
File 'example.txt' does not exist.
STDERR
(empty)

Was this helpful?

Related Questions