Cap'n Steve has asked for the wisdom of the Perl Monks concerning the following question:

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"; } }

Replies are listed 'Best First'.
Re: Guessing source code depth with Perl.
by chromatic (Archbishop) on Nov 21, 2007 at 09:54 UTC

    This looks like a job for Text::Balanced. You might have to extract quoted strings first, then analyze the remaining code for curlies, but I'd start with that.

      Interesting module, I'll have to read up on that.
Re: Guessing source code depth with Perl.
by cdarke (Prior) on Nov 21, 2007 at 09:52 UTC
    Maybe use caller in fetch_hook?
      fetch_hook() is actually a PHP function, I'm just gathering information about the code with Perl.
Re: Guessing source code depth with Perl.
by SuicideJunkie (Vicar) on Nov 21, 2007 at 15:43 UTC

    If you want to count braces, you probably need to skip over any braces which occur inside quotes/strings, or in comments.

    Code such as $sub_braces += () = $_ =~ /\{/g; itself will introduce mismatches if you don't filter them out.