I have a Perl script that generates a wiki based on some PHP files. There are hooks within the PHP files and I want the wiki to show which functions, methods, or classes contain the hooks (basically I need the block where fetch_hook() is called).

My first try was to just count the opening and closing curly braces, but that fails because somewhere there must be an unmatched brace in a string.
This is the relevant piece:
open my $file, '<', $_ or die "Couldn't read file $_: $!"; while (<$file>) { # try and guess how deep we are to see when the containing blo +ck ends $braces += () = $_ =~ /\{/g; $braces -= () = $_ =~ /\}/g; if ($in_a_method) { $sub_braces += () = $_ =~ /\{/g; $sub_braces -= () = $_ =~ /\}/g; } # I hope no one uses curly braces in a string... if ($braces < 0 || $sub_braces < 0) { die "Hook finder failed in $filename, line $line."; } # check to see if any block finished if ($braces == 0) { undef $in_a_class; undef $in_a_function; } elsif ($sub_braces == 0) { undef $in_a_method; } # see if we're entering a class if (/class\s+(.+?)\s+\{/) { $in_a_class = $1; $braces = 1; } # or a function elsif (/function\s+(.+?)\s+\{/) { $in_a_function = $1; $braces = 1; } # or a method elsif ($in_a_class && /function\s+(.+?)\s+\{/) { $in_a_method = "$in_a_class::$1"; $sub_braces = 1; } # this is where the hook code is fetched (although it's not ne +cessarily used here :/) elsif (/vBulletinHook::fetch_hook\('(.+?)'\)/) { $options{'debug'} > 1 && print "Found hook $1 in $_\n($in_ +a_function, $in_a_class, $in_a_method)\n"; } }

In reply to Guessing source code depth with Perl. by Cap'n Steve

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.