LoginSignup
0
0

More than 5 years have passed since last update.

Perl6 Cookbook ディレクトリ内のすべてのファイルを処理する

Posted at

こんばんは :whale2:

Perl6でディレクトリの中身を取得する方法です。

Perl5 だと

9.5. Processing All Files in a Directory

opendir 関数でディレクトリをオープンして readdir 関数で中身を取得したりできましたよね。

use v5.18;

# カレントディレクトリ直下のファイル一覧を出力
my $dirname = '.';

opendir(my $dir, $dirname) or die "can't opendir $dirname: $!";
while (defined( my $file = readdir( $dir ) )) {
  next if $file =~ /^\.\.?$/;     # skip . and ..
  say "$dirname/$file";
}
closedir($dir);

Perl6 では

dir 1 を使って下記のように書けます。

use v6;

for dir() -> $fileobj {
  # dir() が返すのは IO::Path 型なので、Strに変換
  say $fileobj.Str ;
}

# または Hyper method call operator (>>) で dir() の結果を Str に
for dir()>>.Str -> $file {
  say $file ;
}

フィルタリング

dir の結果はデフォルトでは...が除かれています。2
dirtest パラメータに条件を指定することで、走査結果をフィルタすることができるので、...も含めるのなら * を指定したりします。

use v6;

dir( test => * )>>.Str.map({.say}) ;

dir をメソッドで使うなら下記のような感じに。

use v6;

# カレントディレクトリから、拡張子が .pl か .pl6 のファイル (大文字小文字区別しない) を探す
for '.'.IO.dir(  test => rx/ '.' :i pl6? $/ )>>.Str -> $file {
  say $file ;
}

再帰的に探す

サブディレクトリの中身も全部走査してみる。3

use v6;

my sub ふぁいんど ( IO::Path $dirname ) {
  $dirname.Str.say;

  for $dirname.dir -> $file {
    # ディレクトリで、かつシンボリックリンクでは無かったら
    # さらにそのディレクトリの中をしらべる
    if $file.d and not $file.l {
      ふぁいんど( $file );
    }
    else {
      $file.Str.say;
    }
  }
}


ふぁいんど( '.'.IO );

おわりです。

参考と注釈


  1. IO::Path  

  2. dir( test => none('.', '..') ) なんですって 

  3. それならfindコマンドでいいよね 

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0