Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Finding a pattern to split on

by urburp (Initiate)
on Dec 05, 2000 at 00:56 UTC ( #44851=perlquestion: print w/replies, xml ) Need Help??

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


I've got file I want to split into chunks, but I'm not sure where the newlines and spaces lie, or how they are interwoven.

It's got the basic structure:

Title Line (\n?)

(4 spaces)Author Line (\n?)

(4 spaces)URL Line (\n?)

... Repeat

However there are things interwoven like header lines:


BLAH Header


Now my question ;) :

if I split the file using: s/\n/ms

I get a string of 0's and 1's


I just *know* this is useful information, but how can I incorporate it into a (relatively) simple pattern match??

Replies are listed 'Best First'.
Re: Finding a pattern to split on
by kilinrax (Deacon) on Dec 05, 2000 at 01:00 UTC
    You don't want to split the file using s/\n/ms, that's a substitution operator. Use /\n/, a match operator.

      Sorry, meant:

      split /\n/sm


        The following code should work fine, assuming $data contains what you're trying to split:
        #!/usr/bin/perl -w use strict; my $data = q|Title Line Author Line URL Line |; my @data = split /\s*\n\s*/, $data; my $i; for ($i=0; $i<=$#data; $i++){ print "$i: $data[$i]\n"; }
        However, if you're reading from a file, i suspect you want something more like this:
        #!/usr/bin/perl -w use strict; open DATA, 'splitdata.txt'; my @data; while (<DATA>) { chomp; s|^\s+||; s|\s+$||; push @data, $_; } my $i; for ($i=0; $i<=$#data; $i++){ print "$i: $data[$i]\n"; }

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2022-06-29 13:00 GMT
Find Nodes?
    Voting Booth?
    My most frequent journeys are powered by:

    Results (96 votes). Check out past polls.