Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Regular expression match in file

by perlsen (Chaplain)
on Feb 10, 2005 at 11:41 UTC ( [id://429664]=perlquestion: print w/replies, xml ) Need Help??

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

Hi, Monks, i have the text file which contains various levels and their text.
I have to match the texts in the one level to next level that should be stored in the arrays.
Can u give some suggestions.

text file inputs: level 1 section1 section2 level 2 section3 section4 level 2 output needed @array[0]: level 1: section1 section2 @array[1]: level 2: section3 section4
Thanks in advance.

Replies are listed 'Best First'.
Re: Regular expression match in file
by gopalr (Priest) on Feb 11, 2005 at 06:29 UTC

    Hi,

    Use Array Reference.

    $file=' level 1 section1 section2 level 2 section3 section4 level 2 '; while ($file=~s#(level [0-9].+?)(level [0-9])#$2#s) { $a=$1; @b=$a=~m#(section[0-9])#g; push (@array, [@b]) }
Re: Regular expression match in file
by holli (Abbot) on Feb 10, 2005 at 12:02 UTC
    use strict; use warnings; use Data::Dumper; my %levels = (); my $level = 0; while (<DATA>) { chomp; if (/^level (\d+)/) { $level = $1; } elsif (/^section(\d+)/) { push @{$levels{$level}}, $_; } } print Dumper (\%levels); __DATA__ level 1 section1 section2 level 2 section3 section4 level 2
    Output:
    $VAR1 = { '1' => [ 'section1', 'section2' ], '2' => [ 'section3', 'section4' ] };
    holli, /regexed monk/
Re: Regular expression match in file
by cog (Parson) on Feb 10, 2005 at 11:45 UTC
    while (<>) { if (/^level (\d+)/) { $i = $1; } else { $array .= $_; } }

    Does that do the trick?

Re: Regular expression match in file
by reneeb (Chaplain) on Feb 10, 2005 at 11:58 UTC
    I would use the following code:
    #! /usr/bin/perl use strict; use warnings; use Data::Dumper; my $file = './test.txt'; my @array; { local $/ = "\nlevel"; open(FILE,"<$file") or die $!; while(my $entry = <FILE>){ chomp $entry; $entry = 'level'.$entry unless($entry =~ /^level/); push(@array,$entry); } } print Dumper(\@array);

Log In?
Username:
Password:

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

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

    No recent polls found