関数順 インデックス
目的別 インデックス

構文
 
 opendir ディレクトリ・ハンドル, ディレクトリ名

返り値
 
 ・ディレクトリのオープンに成功した場合に真

説明

  • ディレクトリ名という名前のディレクトリをオープンしてディレクトリ・ハンドルに結びつけます。readdir関数にディレクトリ・ハンドルを渡すことによってディレクトリのエントリを取得することができます。

使用例

ディレクトリ/home/user1の中の一覧を表示する
#!/usr/bin/perl
use strict;
use warnings;

my $dirname = '/home/user1';
opendir my $dh, $dirname or die "$!:$dirname";
while (my $dir = readdir $dh) {
  print "$dir\n";
}
closedir $dh;
ディレクトリ/home/user1の中のファイルの一覧を表示する
#!/usr/bin/perl
use strict;
use warnings;

my $dirname = '/home/user1';
opendir my $dh, $dirname or die "$!:$dirname";
while (my $dir = readdir $dh) {
  my $fullpath = "$dirname/$dir";
  next unless -f $fullpath;
  print "$fullpath\n";
}
closedir $dh;
※ファイルだけの一覧が欲しい場合はファイル・テスト演算子の-fを使います。

ディレクトリ/home/user1の中のCSVファイルの一覧を表示する
#!/usr/bin/perl
use strict;
use warnings;

my $dirname = '/home/user1';
opendir my $dh, $dirname or die "$!:$dirname";
while (my $dir = readdir $dh) {
  my $fullpath = "$dirname/$dir";
  next unless $fullpath =~ m/\.csv$/i;
  next unless -f $fullpath;
  print "$fullpath\n";
}
closedir $dh;
※正規表現などを使って特定のファイルのみを取得することもできます。

ディレクトリ/home/user1の中のCSVファイルの一覧を表示する(globを使用)
#!/usr/bin/perl
use strict;
use warnings;

my $search = '/home/user1/*.csv';

while (my $file = glob($search)) {
  print $file, "\n";
}
※ワイルドカードを使ってファイル名を指定するのであればglobを使うという 方法もあります。