Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

slurping (matching \n)

by GaijinPunch (Pilgrim)
on Apr 18, 2005 at 01:10 UTC ( [id://448708]=perlquestion: print w/replies, xml ) Need Help??

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

Hey monks. Quick question. When in slurp mode, is there anyway to match a newline character other than "\n" ? At the moment I don't need to, but probably will at one point.

Example:
local $/ = undef; my $names = <DATA>; $names =~ /First: (\w+)\nSecond: (\w+)\nThird: (\w+)/; my ( $first, $second, $third ) = ( $1, $2, $3 ); print "$first, $second, $third\n"; __DATA__ First: Bob Second: Me Third: You
The above works, but if I try to replace "\n" in the regex with something else which I would assume would work (namely * or .+) I of course get complaints. Yes, I know that newline characters are special, but if you can't recognize them with a wildcard, isn't slurp mode kinda pointless? The data I'm slurping now is very pretty and well layed out, but what if I was slurping a news article or something?

I'm sure I'm missing something important, so please -- feel free to verbally pound me now.

Replies are listed 'Best First'.
Re: slurping (matching \n)
by BrowserUk (Patriarch) on Apr 18, 2005 at 01:15 UTC

    Take a look at the /s modifier. It allows . to also match \n.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco.
    Rule 1 has a caveat! -- Who broke the cabal?
      And that'd be what I was missing. :) Thanks
Re: slurping (matching \n)
by bart (Canon) on Apr 18, 2005 at 04:20 UTC
    Also note that /\s/ always matches a newline, too. You don't need /s for that.
      As do \C, \D, \W, and \X.
Re: slurping (matching \n)
by maa (Pilgrim) on Apr 18, 2005 at 07:44 UTC

    Bear in mind that you might get bitten in longer programs if you don't actually localise your local lexically.

    { local $/ = undef; my $names = <DATA>; } #$/ is back to our original record separator #(which you can use in the regexp if you want) e.g. if ( $names =~ m|First: (\w+)$/Second: (\w+)$/Third: (\w+)|s ) { .... }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://448708]
Approved by Zaxo
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2024-04-25 08:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found