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

Hello,

I have to give Directory name as command line argument and read all the files in that Directory one by one. How to do it? Kindly help.

Example : perl perlscript.pl dir_name (dir_name is a directory containing few text files, Need to read all of them one by one)

Best Wishes,
-Max
  • Comment on Directory name as command line argument

Replies are listed 'Best First'.
Re: Directory name as command line argument
by kyle (Abbot) on Mar 27, 2008 at 17:47 UTC
Re: Directory name as command line argument
by Pancho (Pilgrim) on Mar 27, 2008 at 17:54 UTC
    use strict; use warnings; my $dir = shift @ARGV; # Get first command line argument opendir DIR, $dir or die $!; # Open Directory for my $file ( readdir(DIR) ){ # Loop through reading each file print "$file \n"; }
    Pancho
      Great Help. You are life saver :)
Re: Directory name as command line argument
by hesco (Deacon) on Mar 27, 2008 at 18:17 UTC
    You might also consider using File::Util, as well. Its designed for just this sort of activity, ONCE you have passed your directory name into the script, that is.

    -- Hugh

    if( $lal && $lol ) { $life++; }
      Ohk, Thank you very much....
      if( $lal && $lol ) { $life++; }
      Now that's awesome code :D
Re: Directory name as command line argument
by Narveson (Chaplain) on Mar 27, 2008 at 17:55 UTC
    use strict; use warnings; use Fatal qw(chdir open); my ($dir_name) = @ARGV; chdir $dir_name; for my $file (grep {-f} glob '*') { open my $reader, '<', $file; print "Just opened $file.\n"; while (<$reader>) { # Did you want to do anything besides read the file? } print "Just finished reading $file.\n"; }
      Nice code, great help, Thanks you very much :) Have to do some pattern matching in each file and few other stuff, its simple......thanks again :)