「すぐわかるPerl」 8.10 ディレクトリのリカーシブ処理(その2)
■ワードカウントさせてみよう
「すぐわかるPerl」 8.10 ディレクトリのリカーシブ処理(その1)でやったtreeにワードカウント機能をつけてみる。(ただし、半角で区切りを判断するので、英語用かな)
- $depをグローバル変数にして使ってみる。(現在いる階層の深さ)
- $awcという変数を全ワードカウントの累計につかう。
- -Tはテキストファイルの場合に真になるファイルチェック演算子
- -Bはバイナリファイルの場合に真になるファイルチェック演算子
- ワードカウントの方法は、wcコマンドの出力を空白でsplitした3番目の要素を使う
- $dwcにはディレクトリごとのワード数を累計する
#! /usr/local/bin/perl
# tree .. カレントディレクトリ以降のファイルリストを作成
# ワードカウントもあるよ$dir = 'pwd';
print $dir;
$dep =1;
$awc = 0;
&dirproc;
if ($awc > 0){
print "\n*** this directory has $awc words test files in total.\n";
}sub dirproc {
my(@files , $file , $dwc);
@files = sort(glob("*"));
foreach $file(@files) {
if (-T $file){
@t=split(/\s+/,`wc $file`);
for ($i = 1; $i <= $dep; $i++){
print "|\t";
}
print $file."\t".$t[2]."\n";
$dwc += $t[2];
$awc += $t[2];
}
}if ($dwc > 0){
for ($i = 1; $i <= $dep; $i++){
print "|\t"
}
print "\n*** this directory has $dwc words test files in total.\n";
}foreach $file(@files) {
if (-B $files and -f $file){
for ($i =1; $i <= $dep; $i++){
print "|\t";
}
print $file."\n";
}
}foreach $file(@files) {
if (-d $file){
for ($i = 1; $i <= $dep; $i++){
print "|\t";
}
print $file."\n";
++$dep;
chdir($file);
&dirproc;
chdir(".." or die "waaaa");
--$dep;
}
}
}
| 固定リンク | コメント (0) | トラックバック (0)








