Perl練習、再帰とファイルシステムの扱い
カレントディレクトリ以下からC++のソース、ヘッダを見つけて列挙
use strict; sub FindFile { my ($dir, $pred, $operator) = @_; my @list = (); opendir(DIR, $dir) or die("Can not open directory : $dir ($!)"); @list = readdir(DIR); closedir(DIR); foreach my $file (sort @list) { next if( $file =~ /^\.{1,2}$/ ); my $path = "$dir/$file"; if( -d $path) { FindFile($path, $pred, $operator); } else { $operator->do_($path) if( $pred->do_($path) ); } } } package pred; use File::Basename; sub new { my $class = shift; my $self = { ext_ => shift }; return bless $self, $class; } sub do_ { my $this = shift; my $path = shift; my ($name, $path, $ext) = fileparse($path, $this->{ext_}); return $ext; } package operator; sub new { my $class = shift; my $self = {}; return bless $self, $class; } sub do_ { my $this = shift; my $path = shift; print $path . "\n"; } package main; my $ext = qr/(\Q.cpp\E|\Q.hpp\E|\Q.h\E)/; my $pred = new pred( $ext ); my $op = new operator(); FindFile('.', $pred, $op);
C++のoperator()みたいなことができたらdo_とか使わないんだけど