#! perl -slw use strict; use List::Util qw[ min ]; $|=1; ## Mildly cleaned up version with edgecase bug. sub indexBal { my( $string, $lookFor, $limit ) = @_; my $nesting = 0; for( my( $position, $char ) = ( 0, substr $string, 0, 1 ); $position < min( length( $string ) , $limit ); $char = substr $string, ++$position, 1 ) { $nesting++ if $char =~ m/[\[\{]/; $nesting-- if $char =~ m/[\]\}]/; die 'Unbalanced' if $nesting < 0; return $position if $char eq $lookFor and $nesting == 0 } return; } my $depth = 0; my $indent = ' '; my $string = ''; my $_print = sub { print $indent x $_[2], substr( $_[0], 0, $_[1], '' ); $_[0] =~ s[^\s*][]; }; sub pp { my( $s, $max_width, $EOS ) = @_; $string .= $s; while( length( $string ) > $max_width or $EOS ) { my ($pos, $first ) = ( pos $string, $1 ) if $string =~ m/([\[\{\]\},])/g; return unless defined $pos; if ( defined $first and $first ne ',' ) { if ( $first =~ m/[\]\}]/ ) { $_print->( $string, ++$pos, --$depth ); } elsif ( defined( my $newpos = indexBal( $string, $first eq '[' ? ']' : '}', $max_width ) ) ) { $_print->( $string, $newpos + 2, $depth ); } else { $_print->( $string, $pos, $depth++ ); } } else { $_print->( $string, $pos, $depth ); } } return; } ## Test harness only below here my $data = ; my $width = $ARGV[ 0 ]||100; $indent = $ARGV[ 1 ] if @ARGV == 2; while( length $data ) { my $p = 1+rindex( $data, ',', $width+rand( 50 ) )||length $data; my $sub = substr( $data, 0, $p, '' ); pp( $sub, $width, !length $data ); } __DATA__