I still think your code is doing a lot of manual pattern matching which could be better done by the regex engine.

By that, I assume you mean the indexBal() routine.

If you can encapsulate this into a more efficient, or more simple routine by using the regex engine, please do, it would help me a lot. I tried and failed.

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 $s = '{ [ { [ { x }, { y } ], [ z ] } ] } { [ { '; my $pos = indexBal $s, '}', length( $s ); print substr $s, 0, $pos+1; { [ { [ { x }, { y } ], [ z ] } ] }

Note that:

  • The brackets and braces may be nested to any arbitrary depth.
  • The requested match may not yet be available.
  • There will nearly always be an incomplete set of nested brackets on the end of the string.
  • The routine takes a parameter that specifies the maximum length in which the match must be found else don't bother looking any further.

    Examine what is said, not who speaks.
    Silence betokens consent.
    Love the truth but pardon error.

    In reply to Re^4: Refactoring challenge. by BrowserUk
    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.