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);