Getting directory, File list from path.
Source.
use File::Find; # for File find
use Cwd 'abs_path'; # for Absolutely path
sub fnGetDirFileList ### (Directory path{string}[, Find extension{string}[, Tracing sub-directory{bool}[, Type{string}]]]) return FileList{Array};
{
#
### Example: &fnGetDirFileList("C:\\Test", "txt|in?(i|f)", 1, "f")
### Example: &fnGetDirFileList("C:\\Test", ".*", 1, "f")
### Example: &fnGetDirFileList("C:\\Test", "", 1, "d")
### Example: &fnGetDirFileList("C:\\Test", "txt|in?(i|f)", 1, "a")
### Example: &fnGetDirFileList("test", "in?(i|f)", 1, "a")
### http://open-source.tistory.com
### by fckorea.
### Code written by fckorea. [2013-02-03]
#
my ($sDirectory, $sExtension, $bSubDirectory, $sCheck) = @_;
my $sRegex;
my @aDirFileList;
# Extension except
return undef if(($sDirectory eq undef) or (-f abs_path($sDirectory)));
$sExtension = ".*" if($sExtension eq undef);
# Exception
$bSubDirectory = 0 if($bSubDirectory eq undef);
$sCheck = "f" if(($sCheck eq undef) or (grep{ $_ ne $sCheck } ("a", "d", "f")));
$sCheck = lc($sCheck);
# Absolutely path setting.
$sDirectory = abs_path($sDirectory);
if($bSubDirectory)
{
find( sub { push @aDirFileList, $File::Find::name if ((-f $File::Find::name) and (($File::Find::name =~ m/\.($sExtension)$/i) or ($sExtension eq ".*"))); }, $sDirectory) if(($sCheck eq "f") or ($sCheck eq "a"));
find( sub { push @aDirFileList, $File::Find::name if ((-d $File::Find::name) and ($File::Find::name ne $sDirectory));}, $sDirectory) if(($sCheck eq "d") or ($sCheck eq "a"));
}
else
{
opendir(hDIR, $sDirectory) or die $!;
while(my $sFile = readdir(hDIR))
{
push @aDirFileList, "$sDirectory/$sFile" if((-f "$sDirectory/$sFile") and (($sFile ne ".") and ($sFile ne "..")) and (($sCheck eq "f") or ($sCheck eq "a")) and (($sFile =~ m/\.($sExtension)$/i) or ($sExtension eq ".*")));
push @aDirFileList, "$sDirectory/$sFile" if((-d "$sDirectory/$sFile") and (($sFile ne ".") and ($sFile ne "..")) and (($sCheck eq "d") or ($sCheck eq "a")));
}
}
# General Path ('\' => '/' change)
for (my $i = 0 ; $i <= $#aDirFileList; $i++)
{
$aDirFileList[$i] =~ s/\\/\//g;
}
return @aDirFileList;
}
Usage.
# Sample
my @alist = fnGetDirFileList("test", undef, 1, "f");
print "$_\n" foreach(@alist);
'Perl' 카테고리의 다른 글
[ Perl::Function ] fnOptionsParser (0) | 2013.04.18 |
---|---|
[ Perl::Package ] Logger (0) | 2013.03.26 |
[ Perl ] Data Types (0) | 2013.02.17 |