Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: How do I match/extract a function from a JavaScript file?

by Shakya (Initiate)
on Sep 30, 2007 at 17:35 UTC ( #641792=note: print w/ replies, xml ) Need Help??


in reply to How do I match/extract a function from a JavaScript file?

Following definitely works in "not so complex" scenarios

#!/usr/bin/perl use strict; my $Jscript = join (" ",<DATA>); # Extract function foo from Jscript my $content = _extract("foo",$Jscript); sub _extract { my ($funct,$Jscript) = @_; my ($round,$curly); $round = qr!\(([^()]*|(??{$round}))*\)!; $curly = qr!\{([^{}]*|(??{$curly}))*\}!; if ($Jscript =~ m!($funct\s*$round\s*$curly)!ms) { print "Matched :\n",$1; } } __DATA__ foo (a, b, c) { if (c) { a++; } else { b--; } print "hi"; } fum (d, e, f, g, h) { if (d) { e++; } else { f = g + h; } print "ho"; }
Output is :
Matched : foo (a, b, c) { if (c) { a++; } else { b--; } print "hi"; }
On more explanation on matching nested parentheses, you can refer Friedl's Mastering Regular Expressions, page 330.


Comment on Re: How do I match/extract a function from a JavaScript file?
Select or Download Code
Replies are listed 'Best First'.
Re: Answer: How do I match/extract a function from a JavaScript file?
by erroneousBollock (Curate) on Sep 30, 2007 at 17:43 UTC
    sub _extract { my ($funct,$Jscript) = @_; my ($round,$curly); $round = qr!\(([^()]*|(??{$round}))*\)!; $curly = qr!\{([^{}]*|(??{$curly}))*\}!; if ($Jscript =~ m!($funct\s*$round\s*$curly)!ms) { print "Matched :\n",$1; } }
    err, I can't see where you've matched the function keyword or the function operator anywhere in your code. That would seem to be a prerequisite to parsing out functions from ECMAScript source.

    foo (a, b, c) { if (c) { a++; } else { b--; } print "hi"; } fum (d, e, f, g, h) { if (d) { e++; } else { f = g + h; } print "ho"; }
    That's not valid EMCAScript.

    -David.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://641792]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (8)
As of 2015-07-07 23:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (93 votes), past polls