ファイルサイズを取得する
ファイルサイズを取得するには、ファイルテスト演算子「-s」を使用します。
-s $file
ファイルサイズの単位はバイトです。
サンプルプログラム
ファイルテスト演算子 -s を使ってファイルサイズを取得するサンプルです。
use strict;
use warnings;
# ファイルのサイズを取得する。
# -s ファイル名
# 単位は、バイトです。
print "1: ファイルのサイズを取得する。 -s\n";
my $file = "a.txt";
if (-f $file) {
my $file_size = -s $file;
print "$file のファイルサイズは、$file_size バイトです。\n\n";
}
else { print "$file は、存在しませんでした。\n\n" }
use strict;
use warnings;
print "2: ファイルサイズがあるバイトを超えたら出力をとめる。\n";
my $file = "output_$$.txt";
if (-e $file) {
die "$file は存在します。\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 "出力後の $file のファイルサイズは、" . -s $file . "バイトです。\n";
close $fh;
while文を使ってファイルサイズが1,000,000バイトを超えたら、停止しています。
Perlゼミ

