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

From perl you want to know the size of a file.

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

    perldoc -f -X
    perldoc File::stat
Revision: 1.4 Reviewed:  

[Top]