Tweet

How do I get the size of a file in Perl?

You want to know the size of a file from Perl.

Solution 1: file test operators

In Perl you can use file test operators. The operator that will provide you with the size of the file is -s:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my $filesize = -s "test.txt";
    print "Size: $filesize\n";

    exit 0;

The output of this might be (depending on the size of test.txt):

    Size: 15

Solution 2: The OO way

The module File::stat provides statistics on files:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use File::stat;

    my $filesize = stat("test.txt")->size;

    print "Size: $filesize\n";

    exit 0;

This would produce identical output to the previous example.

See also

Or from your command line:
  perldoc -f -s
  perldoc File::stat
[Top]