yoda54 has asked for the wisdom of the Perl Monks concerning the following question:

Greetings,

How can I slurp multiple lines to a variable? I have a multiple line range that I need to pull out.

Thanks for any advice!

open(F, "file"); while(<F>) { if (/StartPattern/.../StopPattern/) { # if matches, slurp all of this contents to a variable } close(F);

Replies are listed 'Best First'.
Re: Slurp multiple lines to a variable
by aaron_baugher (Curate) on May 14, 2015 at 01:51 UTC

    You're most of the way there; just define your variable outside the loop and then add the lines to it. Check out the lines I added to your code below. You'll want to use one method or the other, depending on whether you want the lines in an array or as a single string in a scalar.

    open(F, "file"); my $lines = ''; # a scalar to store the lines in my @lines; # an array to store the lines in while(<F>) { if (/StartPattern/.../StopPattern/) { $lines .= $_; # append the line to my scalar push @lines, $_; # add the line to my array } } close(F);

    Aaron B.
    Available for small or large Perl jobs and *nix system administration; see my home node.

      Thanks!
Re: Slurp multiple lines to a variable
by Anonymous Monk on May 14, 2015 at 01:43 UTC

    If you don't want to read the entire file into memory, how about

    my @out; while(<F>) { push @out, $_ if /StartPattern/.../StopPattern/; }