Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Automagically indenting (implementation, code)

by perlmonkey (Hermit)
on May 11, 2001 at 08:18 UTC ( #79638=note: print w/ replies, xml ) Need Help??


in reply to Automagically indenting (implementation, code)

I dont know of any magic regex that can do this. You have to be careful about balancing and all sort of fun stuff like that. I did something like this for formatting some config files at my work and I used Text::Balanced with a twist of recursion. This may not be the best solution for you, but it might give you a start:

use Text::Balanced qw(gen_extract_tagged); my $extract = gen_extract_tagged( 'node\s+\w+\s+\{', # start tag '\}', # end tag '(?s).*?(?=node\s+\w+\s+\{)' # prefix ); # $text is your file contents print indent($extract, $text); sub indent { my( $extract, $text, $depth ) = @_; $text =~ s/^\s+//mg if $depth == 0; if( index($text, '{') == -1 ) { #no more blocks $text =~ s/^/" "x$depth/gme; return $text; } #extract block out of $text my($extracted, $remainder, $prefix, $start, $block, $end) = $extract->($text); $prefix =~ s/^/" "x$depth/gme; my $formatted = $prefix; $formatted .= " " x $depth . $start; # parse the inner block $formatted .= indent($extract, $block, $depth+1) if $block; $formatted .= " " x $depth . $end; # parse what is after this block $formatted .= indent($extract, $remainder, $depth) if $remainder; return $formatted; }

For an input $text of
node myContainer { someParam WhateverWeWerePassed node myNode { fooParam DogPoopMonk node foo2 { stuff more stuff even more stuff node mode2 { stuff } } } }


I got the results of:
node myContainer { someParam WhateverWeWerePassed node myNode { fooParam DogPoopMonk node foo2 { stuff more stuff even more stuff node mode2 { stuff } } } }


Comment on Re: Automagically indenting (implementation, code)
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://79638]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (2)
As of 2014-07-13 06:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (247 votes), past polls