CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [ravi.joshi53] Reading all the files from a directory: Edit Log



Zhris
Enthusiast

Sep 11, 2012, 12:35 PM


Views: 1424
Re: [ravi.joshi53] Reading all the files from a directory

Hi,

As suggested by Laurent_R, glob can be used to neatly read the contents of a directory:


Code
my $dir_path = $ARGV[0]; 

while (<"$dir_path/*">) { print "$_\n"; }


Rather than telling you everything thats wrong with your code, here is an example that prints the first line of every file in the directory supplied. Possibly compare it against your own code to see where you have gone wrong:


Code
#!/usr/bin/perl 
use strict;
use warnings;

my $dir_path = $ARGV[0];

opendir my $dh, $dir_path or die "cannot open dir $dir_path: $!";

foreach my $file_path ( map { "$dir_path/$_" } grep { -f "$dir_path/$_" } readdir $dh )
{
open my $fh, '<', $file_path or die "cannot open file $file_path: $!";

while (my $line = <$fh>)
{
chomp $line;
print "$line\n";
last;
}

close $fh;
}

closedir $dh;


Chris


(This post was edited by Zhris on Sep 11, 2012, 12:50 PM)


Edit Log:
Post edited by Zhris (Enthusiast) on Sep 11, 2012, 12:38 PM
Post edited by Zhris (Enthusiast) on Sep 11, 2012, 12:39 PM
Post edited by Zhris (Enthusiast) on Sep 11, 2012, 12:44 PM
Post edited by Zhris (Enthusiast) on Sep 11, 2012, 12:50 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives