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
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
.