in reply to Re: Refactoring challenge.
in thread Refactoring challenge.

I think your edge case is addressed by putting and length( $string ) back into your while conditional.

I prefer a single chain of if/elsifs to nesting, and I factored out the use of $string as it is invariably the first argument to $_print:

my $string = ''; my $_print = sub { print $indent x $_[1], substr( $string, 0, $_[0], '' ); $string =~ s[^\s*][]; }; sub pp { my( $s, $max_width, $EOS ) = @_; $string .= $s; while ( length( $string ) > ($EOS ? 0 : $max_width) and $string =~ + m/([\Q[]{},\E])/g ) { my ($pos, $first) = ($+[0], $1); if ( ! defined $first or $first eq ',' ) { $_print->( $pos, $depth ); } elsif ( $first eq ']' or $first eq '}' ) { $_print->( ++$pos, --$depth ); } elsif ( defined( my $newpos = indexBal( $string, $first eq '[' ? + ']' : '}', $max_width ) ) ) { $_print->( $newpos + 2, $depth ); } else { $_print->( $pos, $depth++ ); } } return; }

Caution: Contents may have been coded under pressure.