バージョン
- Path::Class 0.33
- Path::Tiny 0.056
オブジェクト生成
Path::Classで生成したオブジェクトは、ファイルはPath::Class::File、ディレクトリはPath::Class::Dirとなる。Path::TinyはどちらもPath::Tinyとなる。
$file = file($path);
$dir = dir($path);
$file = path($path);
$dir = path($path);
ディレクトリ配下のファイルオブジェクト生成
$file = $dir->file($name);
$file = $dir->child($name);
ディレクトリ配下のディレクトリオブジェクト生成
$dir = $dir->subdir($name);
$dir = $dir->child($name);
ディレクトリ削除(配下ファイルごと)
$dir->rmtree;
$dir->remove_tree;
ファイルオープン
$read = $file->openr;
$read = $file->open('<:encoding(cp932)') or die "Can't read $file: $!";
$read = $file->open('<:utf8') or die "Can't read $file: $!";
$read = $file->openr;
$read = $file->openr(':encoding(cp932)');
$read = $file->openr_utf8;
ファイルの内容を配列に読み込み
@lines = $file->slurp( chomp => 1 );
@lines = $file->lines( { chomp => 1 } );
ファイルにまとめて書き込み
$file->spew( iomode => ':utf8', $data );
$file->spew( { binmode => ':utf8' }, $data );
親ディレクトリ名でファイルを作成
file($file->parent)->touch;
$file->parent->touch;
ファイルをコピー
$file->copy_to($path);
$file->copy($path);
ファイルをリネーム
$file->move_to($file_path);
$file->move($file_path);
ファイルを指定ディレクトリに移動
Path::Tinyのmoveはrenameと同等の機能なので注意が必要。
$file->move_to($dir_path);
use File::Copy 'move';
move $file, $dir_path;
ディレクトリ配下のファイルを処理
$dir->recurse( callback => sub {
my $file = shift;
return unless -f $file;
print $file, "\n";
});
my $iterator = $dir->iterator( { recurse => 1 } );
while( my $file = $iterator->() ) {
next unless $file->is_file;
print $file, "\n";
}