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

前端 未结 7 1959
南旧
南旧 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:56

    Open a filehandle using a pipe from "dir" command.

    E.g.

    open my $FOO, "dir|" or die "Can not run 'dir': $!";
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-15 13:59

    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.

    0 讨论(0)
  • 2021-02-15 14:11

    Change

    my $ResultsHandle = "";
    

    to

    my $ResultsHandle;
    
    0 讨论(0)
  • 2021-02-15 14:14

    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
    }
    
    0 讨论(0)
  • 2021-02-15 14:16

    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.

    0 讨论(0)
提交回复
热议问题