Translate

2012年4月8日日曜日

File::Find

■再帰的にディレクトリを移動して、ファイル/ディレクトリ名を取得する

.
├── 1
│   └── 2
│       └── 3.txt
├── a
│   └── b.txt
└── Sample.pl

上記構成を例に使用してみる。
■"1"ディレクトリの構成を調べる
#!/usr/bin/perl
use feature 'say';
use strict;
use warnings;
use utf8;
use File::Find;


find(\&wanted, '1');                                                                    

sub wanted{
  say "CurrentDirectory :", $File::Find::dir;
  say "Name             :", $_;
  say "FullPath         :", $File::Find::name;
  say "---";
}

実行結果:
CurrentDirectory :1
Name             :.
FullPath         :1
---
CurrentDirectory :1
Name             :2
FullPath         :1/2
---
CurrentDirectory :1/2
Name             :3.txt
FullPath         :1/2/3.txt
---



■複数のディレクトリを指定してみる
#!/usr/bin/perl
use feature 'say';
use strict;
use warnings;
use utf8;
use File::Find;


find(\&wanted, qw/1 a/); #配列で指定

sub wanted{
  say "CurrentDirectory :", $File::Find::dir;
  say "Name             :", $_;
  say "FullPath         :", $File::Find::name;
  say "---";
}

実行結果:
CurrentDirectory :1
Name             :.
FullPath         :1
---
CurrentDirectory :1
Name             :2
FullPath         :1/2
---
CurrentDirectory :1/2
Name             :3.txt
FullPath         :1/2/3.txt
---
CurrentDirectory :a
Name             :.
FullPath         :a
---
CurrentDirectory :a
Name             :b.txt
FullPath         :a/b.txt
---



■一番下の階層からスタートする
#!/usr/bin/perl
use feature 'say';
use strict;
use warnings;
use utf8;
use File::Find;


finddepth(\&wanted, '1');

sub wanted{
  say "CurrentDirectory :", $File::Find::dir;
  say "Name             :", $_;
  say "FullPath         :", $File::Find::name;
  say "---";
}

実行結果:
CurrentDirectory :1/2
Name             :3.txt
FullPath         :1/2/3.txt
---
CurrentDirectory :1
Name             :2
FullPath         :1/2
---
CurrentDirectory :1
Name             :.
FullPath         :1
---

0 件のコメント:

コメントを投稿