Perl-users.jp

クロスプラットフォームなファイル・ディレクトリパスの操作

Path::Classを使うとファイルやディレクトリの操作ができます。

ディレクトリ操作

use Path::Class qw(dir); 
my $dir = dir('foo', 'bar');
# もしくは
use Path::Class::Dir;
my $file = Path::Class::Dir->new('foo', 'bar');

# Windowsだったらfoo\bar
# Unixだったらfoo/bar で表示される
print "$dir\n";

# サブディレクトリの取得
my $subdir = $dir->subdir('baz'); #foo/bar/baz

# 親ディレクトリの取得
my $parent = $dir->parent; # foo 

# 絶対パスの取得
my $abs = $dir->absolute; # /path/to/current/foo/bar

# ディレクトリ以下の表示
while (my $file = $dir->next) {
    print "$file\n"; # ファイルかサブディレクトリ
}

# ディレクトリの削除
$dir->remove; # ディレクトリが空じゃないとダメ

ファイル操作

use Path::Class qw(file);
my $file = dir('hoge', 'fuga.txt');
# もしくは
use Path::Class::File;
my $file = Path::Class::File->new('hoge', 'fuga.txt');

# Windowsだったらhoge\fuga.txt
# Unixだったらhoge/fuga.txt で表示される
print "$dir\n";

# ディレクトリの取得
my $dir = $file->dir; # hoge

# 絶対パスの取得
my $abs = $file->absolute; # /path/to/current/hoge/fuga.txt

# 読み込みモードでファイルハンドルの取得
my $fh = $file->open('r') or die $!;

目次へ

Last modified: $Date: 2008-05-22T09:21:23.154313Z $