I\'m trying to figure out the proper PBP approved way to process a multi line string one line at a time. Many Perl coders suggest treating the multi line string as a filehandle
Open a filehandle using a pipe from "dir" command.
E.g.
open my $FOO, "dir|" or die "Can not run 'dir': $!";
Don't initialise $ResultsHandle
:
use strict;
use warnings;
my $return = `dir`;
my $ResultsHandle; # <-- leave undefined
my $matchLines = "";
my $resultLine = "";
open $ResultsHandle, '<', \$return;
while (defined ($resultLine = <$ResultsHandle>)) {
if ($resultLine =~ m/joe/) {
$matchLines = $matchLines . "\t" . $resultLine;
}
}
close($ResultsHandle);
print "Original string: \n$return\n";
print "Found these matching lines: \n$matchLines\n";
If you leave $ResultsHandle
undefined before the open()
, it will be filled in with a reference to the file handle. Because you were setting it to a string, open()
presumed that it was supposed to be a symbolic reference to a variable instead --- not allowed under use strict
.
The more succinct PBP way is to use open like so:
open my $ResultsHandle, '<', \$return;
This eliminates the need for that earlier "my $Resultshandle;" declaration and avoids incurring that strict warning that you ran into.
Change
my $ResultsHandle = "";
to
my $ResultsHandle;
Better result with split can be done by:
my $result="LINE1
line2
linE3
";
#attention, /^/m allows properly operate on multiline string using regex
#and ^ is character empty begin all lines
foreach my $resultLine (split /^/m, $result) {
print $resultline; #withount '\n' because it have got
#some checks & operations
}
You can also use a regexp as an iterator:
my $data = q{Hello
This
Is
A
Test};
while( $data =~ /(.+)$/mg) {
print "line is '$1'\n";
}
This is slightly less convoluted compared to using a filehandle that represents a string.