Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Perl idioms $/ and q|| to read text file blockwise

Tags:

perl

I'm trying to understand some Perl code that is used to read a text file block-wise.

The text file MYFILElooks like this:

First block
First Line: Something in here
Second Line: More here
Third Line: etc.

Second block
First Line: Something in here
Second Line: More here
Third Line: etc.

The code is used to extract the lines of a block where a regular expression is found (and it works fine, I just want to understand it).

This is the part of the code that I don't understand:

local $/ = q||;
while (<MYFILE>) {
    do something;
}

Could someone explain to me what the line local $/ = q||; is doing?

like image 365
atreju Avatar asked Sep 16 '13 08:09

atreju


3 Answers

$/ is the input record separator. "This influences Perl's idea of what a "line" is". Setting it to empty string, i.e., '' causes the blank line to split the records. q|| notation quotes the stuff within pipes so q|| is the same as ''. You can use a variety of delimiters with the q prefix: q(), q// are also the same.

like image 91
perreal Avatar answered Nov 15 '22 04:11

perreal


local $/ = q||; 

This will treat empty line as "record separator".

local $/ = q||;
    while(<$fh>) {
        # each loop, $_ will be a different record
        # the first will be "First block\nFirst Line: Something in here\nSecond Line: More here\nThird Line: etc.\n\n"
        # etc.
      }
like image 29
Nikhil Jain Avatar answered Nov 15 '22 06:11

Nikhil Jain


local $/ = q||; is same as local $/ = '';

Check Quote and Quote-like Operators.

local will temporarily using dynamic scope set global variable $/ (input record separator) to empty string, so input records are terminated by one or more empty lines.

like image 32
mpapec Avatar answered Nov 15 '22 06:11

mpapec