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

I have some data in file as

<1>one</1> data data data data <2>two</2> data data data data <3>three</3> data data data data <3>blah</3> data data data data <2>blah</2> data data data data <4>zoom</4> data data data data <4>zoom</4> data data data data <1>data</1>

i need the output as

<1>one data data data data <2>two data data data data <3>three data data data data </3> <3>blah data data data data </3> </2> <2>blah data data data data <4>zoom data data data data </4> <4>zoom data data data data </4> </2> </1> <1>data data data data data </1>

The closing should be as the in nested order.

Replies are listed 'Best First'.
Re: Section Handling - Nested
by tobyink (Canon) on Jun 20, 2013 at 22:20 UTC

    What have you tried so far? What problems have you encountered?

    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
Re: Section Handling - Nested
by kcott (Archbishop) on Jun 20, 2013 at 22:38 UTC
Re: Section Handling - Nested
by hdb (Monsignor) on Jun 21, 2013 at 05:44 UTC

    In your output, where is the last "data data data data" line coming from? In the input there are 7 such lines, in the output, there are 8!

    This is a really nice question and can be very elegantly solved using an array as a stack.

      After I claimed earlier today, that the problem has an elegant solution based on a stack, I have to publish my proposal here, despite the fact that there is no sign that veera has spend any effort on solving this.

      use strict; use warnings; my @stack; while(<DATA>) { if( s|^(<(\d+)>.*)(</\2>\n)|$1\n| ) { print pop @stack while @stack and substr( $stack[-1], 2, -2 ) >= $ +2; push @stack, $3; } print; } print reverse @stack; __DATA__ <1>one</1> data data data data <2>two</2> data data data data <3>three</3> data data data data <3>blah</3> data data data data <2>blah</2> data data data data <4>zoom</4> data data data data <4>zoom</4> data data data data <1>data</1> data data data data