Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'd skip trying to use a complex regex. Instead write a simple parser and build up a tree.</p> <p>Here's a rough and ready implementation. It's only optimized for lazy coding. You may want to use libraries from CPAN to build your parser and your tree nodes. </p> <pre><code>#!/usr/bin/perl use strict; use warnings; my $document = Node-&gt;new(); my $current = $document; while ( my $line = &lt;DATA&gt; ) { if ( $line =~ /^=+\s/ ) { my $current_depth = $current-&gt;depth; my $line_depth = Node-&gt;Heading_Depth( $line ); if ( $line_depth &gt; $current_depth ) { # child node. my $line_node = Node-&gt;new(); $line_node-&gt;heading( $line ); $line_node-&gt;parent( $current ); $current-&gt;add_children( $line_node ); $current = $line_node; } else { my $line_node = Node-&gt;new(); while ( my $parent = $current-&gt;parent ) { if ( $line_depth == $current_depth ) { # sibling node. $line_node-&gt;heading( $line ); $line_node-&gt;parent( $parent ); $current = $line_node; $parent-&gt;add_children( $current ); last; } # step up one level. $current = $parent; } } } else { $current-&gt;add_children( $line ); } } use Data::Dumper; print Dumper $document; BEGIN { package Node; use Scalar::Util qw(weaken blessed ); sub new { my $class = shift; my $self = { children =&gt; [], parent =&gt; undef, heading =&gt; undef, }; bless $self, $class; } sub heading { my $self = shift; if ( @_ ) { $self-&gt;{heading} = shift; } return $self-&gt;{heading}; } sub depth { my $self = shift; return $self-&gt;Heading_Depth( $self-&gt;heading ); } sub parent { my $self = shift; if ( @_ ) { $self-&gt;{parent} = shift; weaken $self-&gt;{parent}; } return $self-&gt;{parent}; } sub children { my $self = shift; return @{ $self-&gt;{children} || [] }; } sub add_children { my $self = shift; push @{$self-&gt;{children}}, @_; } sub stringify { my $self = shift; my $text = $self-&gt;heading; foreach my $child ( $self-&gt;children ) { no warnings 'uninitialized'; $text .= blessed($child) ? $child-&gt;stringify : $child; } return $text; } sub Heading_Depth { my $class = shift; my $heading = shift || ''; $heading =~ /^(=*)/; my $depth = length $1; return $depth; } } __DATA__ = Heading (1) Some text = Heading (2) Some more text == Subheading (3) Some details here == Subheading (3) Some details here = Heading (4) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload