A small point: that s/// is pretty inefficient, and replacing it with:

substr($str, 0, $pos1) = '';
makes it clear that you could do it implicitly in the previous line just by adding an extra argument:
print $indent x $depth, substr( $str, 0, $pos1, '' );

dragonchild's refactored version would not need the $pos = $newpos + 2 correction if the (suitably renamed) $_print() did the same thing.

I'd be tempted to make it read a bit more cleanly by also passing in the depth to $_print() and include a slight reordering to flatten:

my $_consume = sub { print $indent x $_[2], substr $_[0], 0, $_[1], ''; } sub pp { return unless @_; my($str) = @_; my($length, $first) = f1($str); if (!defined $first) { $_consume->($str, $length, $depth); } elsif ($first eq CONST1) {
      $_consume->($str, $length, --$depth);
$_consume->($str, $length + 1, --$depth); } elsif (defined(my $newlen = f2($str, $first))) { $_consume->($str, $newlen + 2, $depth); } else { $_consume->($str, $length, $depth++); } return $str; }

Update: passing $str to be modified in this way is probably not safe - if I remember right, any attached magic will cause a temporary copy to be passed instead - so some slight modifications to pass \$str instead are probably required.

Update 2: added a missing + 1

Hugo


In reply to Re: Refactoring challenge. by hv
in thread Refactoring challenge. by BrowserUk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.