tamaguchi has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to open files without knowing what the filenames are? Suppose I would like to open any file that is a .txt file forexample? Thank you for any help.

Replies are listed 'Best First'.
Re: Fileopening question
by planetscape (Chancellor) on Apr 03, 2006 at 09:41 UTC

    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 = $_; if ($file =~ m/\.(txt)/si) { # do stuff here } } find(\&process_file, $dir);


    Update: Deleted a spurious line from the code. The original is from an example on recursive editing, and I stripped some (but not all) of the non-relevant code. Oops. ;-)

Re: Fileopening question
by tirwhan (Abbot) on Apr 03, 2006 at 09:56 UTC

    planetscape gave the complete answer, here's a simpler option without recursiveness, using glob:

    for my $filename (glob("*.txt")) { next if (!-f $filename); open(my $fh,"<",$filename) or die "Can't open $filename for reading" +; #...process file }

    All dogma is stupid.
Re: Fileopening question
by zentara (Archbishop) on Apr 03, 2006 at 11:41 UTC
    Since you are taking "general purpose", here is a little routine that handles a commonly appearing problem now-a-days, where your encoding can't handle special (but legal) characters in filenames. It won't affect anything, if the filenames are normal ascii, but will fix them, so Perl can find them from the filesystem, if there is a unicode character in them. I was shown this, when I had a problem opening files with Perl, which had names like Claude Gellée , where the funny é is actually an acented e. See Re: problems with extended ascii characters in filenames
    #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;

    I'm not really a human, but I play one on earth. flash japh
Re: Fileopening question
by murugu (Curate) on Apr 03, 2006 at 15:26 UTC
    use glob function.

    Murugesan Kandasamy
    use perl for(;;);