KAKAK
KAKAK

Reputation: 899

Looping between file to store text Perl

sub open_file {
    my @files = @_;
    my @file_text = ();

    foreach my $file(@files){
        open(my $fh, '<', $file);
        @file_text = <$fh>;
        close($fh);
    }
    return @file_text;
}

Hi there. There seems to be a problem with this coding particularly the foreach loop part. @files is an array containing @files = (abc.html bcd.htm zxy.html); I would like to open all these html files and store the accumulative html texts in @file_text for further use.

However i am getting error :

readline() on closed filehandle $fh at source-1-2.pl line 36
readline() on closed filehandle $fh at source-1-2.pl line 36
readline() on closed filehandle $fh at source-1-2.pl line 36

Maybe i am getting three line of same error cause i am looping between 3 html/htm files.

Upvotes: 0

Views: 76

Answers (3)

AdrianHHH
AdrianHHH

Reputation: 14038

As well as the points about open in other answers, the question asks "...open all these html files and store the accumulative html texts in @file_text for further use.". The code has the line @file_text = <$fh>; which will mean the @file_text only has the contents of the last file read. That line might be replaced with @new_text = <$fh>; push @file_text, @new_text; or @new_text = <$fh>; @file_text = (@file_text, @new_text);.

Upvotes: 1

Andomar
Andomar

Reputation: 238076

Perhaps check if the open succeeded:

open(my $fh, '<', $file)
    or die "can't open $file: $!";

Upvotes: 4

TLP
TLP

Reputation: 67900

You should not use open without checking the return value:

open(my $fh, '<', $file) or die $!;
#                        ^^^^^^^^^ this part

What has probably happened is the open failed, so the file handle was never opened.

Upvotes: 3

Related Questions