in reply to Re: Regexp matching on a multiline file: dealing with line breaks
in thread Regexp matching on a multiline file: dealing with line breaks

Hi can you please elaborate more on this statement: my $string =  do { local $/; <DATA>; };
  • Comment on Re^2: Regexp matching on a multiline file: dealing with line breaks
  • Download Code

Replies are listed 'Best First'.
Re^3: Regexp matching on a multiline file: dealing with line breaks
by Athanasius (Archbishop) on Dec 06, 2015 at 13:43 UTC

    We want to read the whole file (in this case, the contents of the __DATA__ section at the end of the script) into the scalar variable $string. Using the diamond operator, a call to <DATA> reads the next line from the filehandle.

    So to read the whole file at once, we need to tell Perl that a “line” is the whole file. In Perl, the special variable $/ (also called $INPUT_RECORD_SEPARATOR and $RS) specifies what terminates a “line,” and undef is a special value which means “read the whole file at once.” See perlvar#Variables-related-to-filehandles.

    Since $/ is a global variable, changing its value can have far-reaching consequences across a large program. It’s therefore good practice to localize any changes to just that part of the code where they’re required. Hence the idiom of declaring the variable with the local declaration and limiting the scope of that declaration by enclosing it in a block. We could say:

    my $string; { local $/; $string = <DATA>; }

    but wrapping it up in a do block is neater and more concise.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,