ディレクトリ内のファイルやフォルダを取得する

perl02  

PERLでディレクトリ内のファイルやフォルダを取得するには、glob関数を使う。

ディレクトリ内のすべてのファイルやフォルダを取得

my @file    = glob "*";

 

拡張子で指定して取得

my @file    = glob "*.cgi";

 

ファイルのみを取得

my @all_entries = glob "*";
my @files = grep { -f $_ } @all_entries; # -f はファイルかどうかをチェック

print "$_\n" for @files;

 

ディレクトリのみを取得

my @all_entries = glob "*";
my @directories = grep { -d $_ } @all_entries; # -d はディレクトリかどうかをチェック

print "$_\n" for @directories;

 

特定のディレクトリを指定する

my @all_entries = glob "data/*";

 

 ./data/*/data/* など、相対パス指定、絶対パス指定が出来る。

 

 

dataディレクトリのフォルダのみを取得して表示

my @all_entries = glob "data/*";
my @directories = grep { -d $_ } @all_entries;

print "$_\n" for @directories;

#もしくは、

foreach $line (@directories){
  print $line . "<br>";
}