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

Hello Monks, I am trying to open a directory that contains lots of files , then I want to grep some information from each file and redrict the output to another file :
-MainDir - dflk.cpp - dll.cpp - cll.cpp .. .. ..
I am familiar with open when dealing with a file but how do you do this with directory :
opendir MainDir or die ""; while <> `grep "theInfolookingfor" fileUnderDir > fileUnderDir.out` cloes dir;
thanks

Replies are listed 'Best First'.
Re: reading from directory
by CubicSpline (Friar) on Aug 19, 2002 at 23:12 UTC
    You're right on track here. The way I usually do this is as follows:

    opendir DIR, "MainDir" or die ""; while( $file = readdir(DIR) ) { #do whatever you want to the file } closedir DIR;

    One thing to note, this method includes directory names.

    If you just want to grep for a string in all .cpp files in the current directory, try using globs (this is still magic to me, btw) like so:

    while( $file = <*.cpp> ) { #do something to the file }

    ~CubicSpline
    "No one tosses a Dwarf!"

      Since there is More Than One Way To Do It, you could also go for the object-oriented approach using DirHandle:
      use DirHandle; my $dh = new DirHandle; $dh->open( 'MainDir' ); foreach ( grep /\.cpp$/, $dh->read ) { # do stuff } $dh->close;
      The DirHandle module is a wrapper around opendir and its relatives, so this is essentially the same as CubicSplines answer, just another way of writing it.

      Cheers,
      --Moodster

Re: reading from directory
by Arien (Pilgrim) on Aug 19, 2002 at 23:56 UTC

    If all you want to do is grep some files, why not actually use grep(1) to do that?

    — Arien

      thanks all :)
Re: reading from directory
by bart (Canon) on Aug 20, 2002 at 14:24 UTC
    IMO you should be using File::Find. That will traverse a whole tree for you.
    use File::Find; find sub { if(-f) { system("grep 'theInfoLookingFor' $_ >$_.out"); } }, $rootdir;