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

Hi all, I have to read several files in perl... e.g. I have all the files with extension .txt
while( defined(my $filename = glob("*.txt"))){ open(WORDLIST,$filename) || die "can't open wordlist: $!";} init_words();
I also tried with
open(WORDLIST, *.txt>);
but am not able to access all the files with .txt extension in the same folder.. Also i want to print the name of the file from which i print some text... e.g. file1.txt has
line1 line2
file2.txt has
line3 line4
I want to get print as:
file1.txt line1 file2.txt line4
Thanking you,

Replies are listed 'Best First'.
Re: read multiple files
by dHarry (Abbot) on Jan 28, 2009 at 11:39 UTC

    use a different file handle for each file or reuse the file handle. You might want to read up on the open statement;-)

Re: read multiple files
by cdarke (Prior) on Jan 28, 2009 at 12:41 UTC
    or use ARGV:
    @ARGV = glob('*.txt'); while (<ARGV>) { # Do some clever stuff with $_ # $ARGV contains the current file name print "$ARGV $_"; }
      ... or even utilise the special iteration of @ARGV ...
      @ARGV = glob('*.txt'); while (<>) { # Do some clever stuff with $_ # $ARGV contains the current file name print "$ARGV $_"; }
      or does that special operation of @ARGV only work for unadulterated i.e. non modified internally to the script, values of @ARGV ??

      There you go, once again living up to my sig :D

      A user level that continues to overstate my experience :-))
Re: read multiple files
by Illuminatus (Curate) on Jan 28, 2009 at 12:49 UTC
    Since you want to use the filename as part of individual file processing, I suggest something like the following:
    use strict; use warnings; my @files = `ls *.txt`; my %filedata; foreach my $file (@files) open (CUR, $file) || die "could not open $file: $!"; my @lines = <CUR>; $filedata{$file} = \@lines; close CUR; }
    I wasn't sure from your question whether you wanted to eliminate duplicate lines from files or not, and if so, dups that appeared only in all files, or just multiple files. That exercise is left to the user...
Re: read multiple files
by Marshall (Canon) on Jan 28, 2009 at 15:39 UTC
    First, you are in what I call "glob Hell". Glob is not portable across even *nix platforms! There is POSIX glob, BSD glob, DOS glob, Windows glob.. Don't even mess with that!

    Open the directory and use grep to find the files that you want:

    opendir (D, "$somepath") || die "couldn't open dir $somepath"; my @txt_files = grep{/.txt$/} readdir D; #note that @txt_files only contains the file names, not #the full path...you will need "$somepath/$filename" in the open
    Ok, now that @text_files has the p2q849-58764310-587.txt, etc. files in some directory. It is not clear to me what you intend to do with them?

    From
    file1.txt line1 file2.txt line4
    I see no pattern or algorithm. Please explain more about what you want to do with these files.