Get the file size
To get the file size , use the file test operator "-s".
-s $file
The unit of file size is bytes.
Example program
This is an example to get the file size using the file test operator -s.
use strict; use warnings; # Get the size of the file. # -s filename # Units are bytes. print "1: Get the size of the file. -S\n"; my $file = "a.txt"; if (-f $file) { my $file_size = -s $file; print "The file size of $file is $file_size bytes.\n\n"; } else {print "$file did not exist.\n\n"}
use strict; use warnings; print "2: Stop printing when the file size exceeds a certain byte.\n"; my $file = "output_$$. txt"; if (-e $file) { die "$file exists.\n"; } open my $fh, ">", $file or die "File open error:$!"; while (-s $file < 1_000_000) { my $string = ('a' x 99) . "\n"; print $fh $string; } print "The file size of $file after output is". -S $file. "Bytes.\n"; close $fh;
If the file size exceeds 1,000,000 bytes using while statement, it is stopped.