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

Hello all,

A quick question: is that possible to use line mode and paragraph mode in differnt parts of the program?

More specifically, I am trying to extract information from thousands of txt files. The names of these txt files are stored in a csv file, in which each line represents the name of a seperate txt file. I want to read the csv file in a "line mode". But when I got the name of each txt file, I would like to extract information from the txt file using the "paragraph mode".

To make things even more complicated, I want to save the extracted information in another newly-created csv file, where each line represented the extracted information from one txt file.

I hope you can give me some suggestions and/or warning for some easy pitfalls to a rookie like me.

Thanks a lot!

  • Comment on Using both line mode and paragraph mode in the same program

Replies are listed 'Best First'.
Re: Using both line mode and paragraph mode in the same program
by ikegami (Patriarch) on Mar 26, 2007 at 19:49 UTC
    Yes. General case:
    # line mode ... { # paragraph mode local $/ = ''; ... } # line mode ...

    Your case:

    sub process_csv { ... open(my $fh, '<', ...) or die(...); while (<$fh>) { ... process_file(...); ... } ... } sub process_file { ... local $/ = ''; open(my $fh, '<', ...) or die(...); while (<$fh>) { ... } ... }

    Beware. If proces_file calls functions, paragraph mode will still be active. That means don't call process_csv (directly or indirectly) from process_file without fixing $/.

Re: Using both line mode and paragraph mode in the same program
by ferreira (Chaplain) on Mar 26, 2007 at 19:53 UTC

    I think local would be your best friend here. You probably can do what you need by defining well contained subroutines which affect the line separator in a minimum scope and then your programming will switch transparently between line and paragraph modes.

    Something like this

    sub read_line { my $h = shift; local $/ = "\n"; return <$h> } sub read_para { my $h = shift; local $/ = ""; return <$h>; } use Fatal qw(open); open H, '<', 'files.csv'; while (my $txt = read_file(*H)) { # process the CSV line and make the filename available in $fn open TXT, '<', $fn; my @paragraphs = read_para(*TXT); # process }
    Warning: The above code is untested.

    Update: ikegami (at Re^2: Using both line mode and paragraph mode in the same program) pointed how "\n\n" is the wrong way to get paragraph mode (as can be read in the docs he mentioned). So I got it right with "".

      Paragraph mode is "". "\n\n" is different. See $/