in reply to Re^2: How to tokenize a RTF file and print it to another file (Update with solution)
in thread How to tokenize a RTF file and print it to another file

Hello Laurent_R

I do agree with you regarding the fact that you might want to access the data again and again, but if this is the case why not load the data into an array and access the array when ever you want instead of keeping the fh open?

Sample of loading data into an array from file:

open my $handle, '<', $path_to_file or die "Not able to open file: $!" +; chomp(my @lines = <$handle>); close $handle or warn "Not able to close file: $!";

Unless if you mean writing to a file. But even though if this was the case I would still prefer to use an array alter the data as much as I want and then when I decide I could use a foreach loop or a join to write the data.

Sample, pseudo code:

open my $fh, '>', "output.txt" or die "Cannot open output.txt: $!"; foreach (@lines) { print $fh "$_\n"; } close $fh or warn "Not able to close output.txt: $!";

An alternative way with join:

print $fh join ("\n", @lines);

I am not saying implying that I am correct, I am just trying to learn more. :D

Let me know what are your thoughts, BR.

Seeking for Perl wisdom...on the process of learning...not there...yet!

Replies are listed 'Best First'.
Re^4: How to tokenize a RTF file and print it to another file (Update with solution)
by Laurent_R (Canon) on Jul 07, 2017 at 17:03 UTC
    Hi thanos1983,

    why not load the data into an array and access the array when ever you want instead of keeping the fh open
    There can be many reasons for not doing that. The most compelling one, which I face almost daily, is that my files often have hundreds of millions of lines. They simply do not fit in memory. And the files I am writing to usually have similar size.

    Even with smaller but still quite large files, it is usually faster to read the file line by line and process each line, rather than copying the data into an array, process each item of the array and then write back the modified array lines

      Hello Laurent_R,

      Well I have read about this again, just never had the case to work such huge files. In these cases I guess you are right.

      Thanks for pointing out. BR

      Seeking for Perl wisdom...on the process of learning...not there...yet!