Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

slurping __DATA__

by LanceDeeply (Chaplain)
on Aug 08, 2003 at 14:11 UTC ( #282185=perlquestion: print w/replies, xml ) Need Help??
LanceDeeply has asked for the wisdom of the Perl Monks concerning the following question:

I know this code:

my $data = do { local $/; <DATA> };
slurps the __DATA__ section into my scalar $data, but what is perl doing in that do loop?

my $data = do { local $/; # localize RS? <DATA> # evaluate <DATA> in scalar context ? }
what's happenning in there?

Replies are listed 'Best First'.
Re: slurping __DATA__
by jeffa (Bishop) on Aug 08, 2003 at 14:17 UTC
    do is "not really a function". It is a block that has a seperate scope from wherever it was called from. This allows you to localize $/ so that when execution leaves our "temporary" scope, $/ will be what it was before it was changed.

    If you look up $/ in perlvar, you will see

       You may set it to a multi-character
       string to match a multi-character terminator, or
       to "undef" to read through the end of file.
    Finally, <DATA> returns the next line from the filehandle DATA, and since $/ is undefined, the entire contents of the file are returned and "caught" in a scalar.

    UPDATE: i should add that this is one of those few cases where local is a good choice. For example,
    local $/;
    Is essentially the same as
    local $/ = undef;
    Which is not the same as
    $/ = undef;
    Even though that last snippet will be contained inside a do block ... $/ will still be undef afterwards. Try this - make two files foo.txt and bar.txt and run this:


    (the triplet paradiddle with high-hat)

      I did read perldoc perlvar but I didnt know that local $/; was undef-ing it for the do's block context. I'll have to go brush up on local, 'cause I never use it.

Re: slurping __DATA__
by Zeroth (Beadle) on Aug 08, 2003 at 14:17 UTC
    See: perldoc -f do
    And read the part about "do BLOCK". That should explain it quite well.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://282185]
Approved by diotalevi
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (10)
As of 2016-10-26 14:30 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (341 votes). Check out past polls.