Reputation: 899
sub open_files {
my @files = @_;
my @lines;
foreach (@files){
print "$_\[1\]\n";
}
foreach my $f (@files){
print "$f\[2\]\n";
open(my $fh,'<',$f) or die " '$f' $!";
print "$fh\[3\]\n";
push(@lines,<$fh>);
close($fh);
}
return @lines;
}
Hi i am having problems with opening files whose absolute path are stored in an array.
What i want to do is go through the array and open each file and then store their data inside @lines
array and then close the file handle.
However i am able to open the .html
files which are stored in the first child directory .e.g /a/abc.html or /b/bcd.html
however it is not opening (or parsing ) the files which are in sub-child directories such as /a/aa/abc.html or /b/bb/bcd.html
I have put in some extra print statements
in my script and numbered their output for the different print lines e.g. [1] [2] [3]
.
This is the result of executing the above code:
The full code is : pastebin Full code
/mnt/hgfs/PERL/assignment/test/a/aa/1 - Copy - Copy (2).htm[1]
/mnt/hgfs/PERL/assignment/test/a/aa/1 - Copy - Copy (2).htm[2]
GLOB(0x898ad20)[3]
/mnt/hgfs/PERL/assignment/test/b/bb/1 - Copy - Copy (2).htm[1]
/mnt/hgfs/PERL/assignment/test/b/bb/1 - Copy - Copy (2).htm[2]
GLOB(0x898ae40)[3]
/mnt/hgfs/PERL/assignment/test/a/1 - Copy - Copy (2).htm[1]
/mnt/hgfs/PERL/assignment/test/b/1 - Copy - Copy (2).htm[1]
/mnt/hgfs/PERL/assignment/test/c/1 - Copy - Copy (2).htm[1]
/mnt/hgfs/PERL/assignment/test/a/1 - Copy - Copy (2).htm[2]
GLOB(0x898ae40)[3]
/mnt/hgfs/PERL/assignment/test/b/1 - Copy - Copy (2).htm[2]
GLOB(0x898ae40)[3]
/mnt/hgfs/PERL/assignment/test/c/1 - Copy - Copy (2).htm[2]
GLOB(0x898ae40)[3]
If you guys need the full code here it is : pastebin Full code
Upvotes: 0
Views: 123
Reputation: 4088
use warnings;
use strict;
die "Usage: $0 (abs path to dir) " if @ARGV != 1;
my $dir = shift @ARGV;
our @html_files = ();
file_find($dir);
print "html files: @html_files\n";
sub file_find {
my $dir = shift;
opendir my $dh, $dir or warn "$dir: $!";
my @files = grep { $_ !~ /^\.{1,2}$/ } readdir $dh;
closedir $dh;
for my $file ( @files ) {
my $path = "$dir/$file";
push @html_files, $file if $file =~ /\.html$/;
file_find($path) if -d $path;
}
}
Upvotes: 2
Reputation: 37146
The short answer is that glob
does not recurse into sub-directories.
Instead, use File::Find
:
use strict;
use warnings;
use feature 'say';
use File::Find 'find';
my @files;
find( sub { push @files, $File::Find::name if /\.html?$/ }, 'base_dir' );
say for @files;
Upvotes: 1