This is the sort of thing I usually use for such purposes. Note this is recursive and therefore will search subdirectories also. :-)
#!/usr/bin/perl -w
# Recurse directories to find .txt files
use strict;
use File::Find;
my $file = '';
my $dir = '';
@ARGV = qw(.) unless @ARGV; # current dir unless otherwise specified
$dir = shift @ARGV;
sub process_file {
return unless -f; #skip directories
$file = $_;
local @ARGV = ($file);
if ($file =~ m/\.(txt)/si) {
# do stuff here
}
}
find(\&process_file, $dir);
HTH,
[planetscape] gave the complete answer, here's a simpler option without recursiveness, using [doc://glob]:
for my $filename (glob("*.txt")) {
next if (!-f $filename);
open(my $fh,"<",$filename) or die "Can't open $filename for reading";
#...process file
}
#this decode utf8 routine is used so filenames with extended
# ascii characters (unicode) in filenames, will work properly
use Encode;
opendir my $dh, $path or warn "Error: $!";
my @files = grep !/^\.\.?$/, readdir $dh;
closedir $dh;
# @files = map{ "$path/".$_ } sort @files;
#$_ = decode( 'utf8', $_ ) for ( @files );
@files = map { decode( 'utf8', "$path/".$_ ) } sort @files;
perlmonks.org content © perlmonks.org and murugu, planetscape, tamaguchi, tirwhan, zentara
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03