Comparing multiple lines in Perl when reading from a file, line by line

Let's say I open the file as follows:

#!/usr/bin/perl open FILE, "8882099"; while ($line = <FILE>) { if ($line =~ /accepted by(.*?)\./s) { print "accepted by: $1"; } } 

the problem is that the regular expression works, but since the file is read line by line, how should I combine this line, which continues to a new line?

thanks

+4
source share
2 answers

Most often, just read the entire file at once.

 my $file; { local $/; $file = <$fh>; } 
+4
source

First of all, you should always use strict and use warnings at the top of each program. This way, you will be shown simple errors that you would otherwise have missed.

Secondly, you should use the names of lexical files, the three-parameter form of open and always check the status of each call to open .

To solve the problem, you should simply search for the line containing the accepted by prefix, and then append the lines to the line you found until you see a complete line match. It is also better to use explicit [^.]+ Than not greedy .*? to avoid backtracking.

Note that you must restore the open file that I commented out and delete the destination $file , since I wrote the program this way for testing purposes.

This solution will have a problem if accepted by is split into multiple lines. If you expect this, then you will need to code something a little different.

 use strict; use warnings; # open my $file, '<', '8882099' or die $!; my $file = \*DATA; my $line; while ($line = <$file>) { if ($line =~ /accepted by/) { $line .= <$file> until $line =~ /accepted by\s*([^.]*)\./; print "accepted by: $1\n"; } } __DATA__ accepted by Tim. accepted by The Financial Director. Today 

Output

 accepted by: Tim accepted by: The Financial Director 
+2
source

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


All Articles