How can I process a multi line string one line at a time in perl with use strict in place?

前端 未结 7 1989
南旧
南旧 2021-02-15 13:32

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

7条回答
  •  时光说笑
    2021-02-15 13:59

    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.

提交回复
热议问题