How can I read paragraphs simultaneously with Perl?

When I write

#!/usr/bin/perl -w use strict; while( <DATA> ) { print "\n-------------------------\n\n"; print; <>; } 

after each "return" I get one line.

Why am I not getting with the following script after each β€œreturn” of one paragraph?

 #!/usr/bin/perl -w use strict; local $/ = ""; while( <DATA> ) { print "\n-------------------------\n\n"; print; <>; } __DATA__ line one line two line three line four line five line six line seven line eigth line nine line ten line eleven line twelve 
+1
source share
3 answers

In your first script, with the $ / variable parameter set to "\ n" by default, <DATA> will only return one line at a time.

I suppose the second script does what you want, just this & lt; > will not interrupt reading on "return", but rather on <ctrl-d> because of your $ / settings (as someone from> noted from reading from STDIN, but I think you already know this and use it to output regulation).

If you really want to adjust the output using "return", you need to do more with $ / in the loop.

  while (<DATA>) {
     print "\ n ------------------------- \ n \ n";
     print;
     $ / = "\ n";  # default so that the following terminates the read on 'return'
     <>;
     $ / = ""; 
 }   
+4
source

I assume you expect this line

 local $/ = ""; 

to change behavior

 <DATA> 

Continue reading until the end of the data.

But actually it takes something like this

 { local $/; # $/ becomes undef in this block ... } 

to enable slurp mode (and enable this mode in the area inside {curlys}).

Essentially, he says: "Forget thinking of new lines as a marker for the end of a record,"

Besides ... there is a link fighter in your code!

 while( <DATA> ) { print "\n-------------------------\n\n"; print; <>; # <-- Feel the power of the DARK SIDE!!! } 

This little guy will read from STDIN, not from DATA - is this really what you want?

+3
source

Using <> in this way (in interactive mode) in paragraph mode will be confusing. It will not return when you press return; instead, it will read until it receives a non-empty line (beginning of a paragraph) and then reads until it receives an empty line (end of this paragraph), then continue reading until it receives a non-empty line (beginning of the next paragraph - which will be buffered, not returned), so he knows that he discarded all the extra empty lines.

Perhaps you should use:

 local $/ = "\n"; <> 

at the end of your cycle. Or maybe POSIX :: getchar ().

+2
source

Source: https://habr.com/ru/post/1305711/


All Articles