ファイルサイズの取得
$a = 'hoge.txt'; $size = -s $a; print "$aのサイズは$sizeです。\n";
ファイルの存在チェック
die "A file called '$filename' already exists. \n" if -e $filename;
または、以下でも同じ
if ( -e $file ){ die "A file called '$filename' already exists. \n"; }
ファイルテストのオプション
- -r 読み込み可能
- -w 書き込み可能
- -x 実行可能で
- -o 実行者とファイルの所有者が同一
- -R 実uid/gidで読み込み可能
- -W 実uid/gidで書き込み可能
- -X 実uid/gidで実行可能
- -O 実uidとファイルの所有者が同一
- -e ファイルが存在する
- -z ファイルサイズが 0
- -s ファイルサイズが 0 以外(大きさを返す)
- -f ファイルは通常ファイル
- -d ファイルはディレクトリ
- -l ファイルはシンボリックリンク
- -p ファイルは名前付きパイプ
- -S ファイルはソケット
- -b ファイルはブロック型の特殊ファイル
- -c ファイルはキャラクタ型の特殊ファイル
- -t ファイルハンドルが tty としてオープンされている
- -u ファイルの setuid ビットがセットされている
- -g ファイルの setgif ビットがセットされている
- -k ファイルの sticky ビットがセットされている
- -T ファイルがテキストファイル
- -B ファイルがバイナリファイル
- -M perl起動時における、ファイルの更新時刻からの日数
- -A perl起動時における、ファイルの参照時刻からの日数
- -C perl起動時における、ファイルの作成時刻からの日数
ファイルの削除
unlink "slate", "bedrock", "lava";
ファイルのリネーム
rename "place/old_file", "new_file";
”.old”で終わるファイルを全て、".new"で終わる名前にリネームする例
foreach my $file (glob "*.old") { my $newfile = $file; $newfile =~ s/\.old$/.new/; if ( -e $newfile ) { warn "Cannot rename $file to $newfile: $newfile exists\n"; } elsif (rename $file, $newfile) { # do nothing } else { warn "Rename $file to $newfile failed: $!\n"; } }
パーミッション変更
chmod 0755, "fred", "barney";
ディレクトリ作成
mkdir "fred", 0755 or warn "Cannot make fred directory: $!";
ディレクトリ削除
rmdir $dir or warn "Cannot rmdir $dir: $!\n";
ディレクトリの移動
chdir "/etc" or die "cannot chdir to /etc: $!";
ディレクトリ中のファイル一覧
ディレクトリ内のリストを得るためには、グロブを使う方法と、ディレクトリハンドルを使う方法がある。以下はディレクトリハンドルを使用した例。
my $dir_to_process = "/etc"; opendir DH, $dir_to_process or die "Cannot open $dir_to_process: $!"; foreach $file (readdir DH) { print $file; } closedir DH; whileを使うと、 while ($name = readdir DH) { next if $name =~ /^\./; # ドットファイル除外 next if $name eq "." or $name eq ".."; # カレントと親ディレクトリ除外 print $name; }