[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] Parsing (simple)



This is probably old hat for most of you, but it brought me some fun:

Problem: a database stores snippets of parsing code (basically, a hairy
regex and some "$foo=$1" assignments). I want to extract the variables
necessary to use the code ($foo) so they can be pre-declared ("use strict"
is in force).

Ugly solution: parse the code snippet, looking for things that look like
assignment statements. Not so easy, as some coders used

$foo = $1; $goo = $2;

and some did

($foo,$goo) = ($1,$2);

and so on.

Elegant (fun) solution: use perl itself.

$snippet = "...";  # long, hairy code here.
eval "package code; $^W=0; $snippet";
@variables = keys %code::;
undef %code::;  # because this is in a loop

P.S.: the "keys %code::" is probably _not_ a general solution, as the code
snippet could contain non-scalars, maybe even file handles, but in this
particular case it doesn't.

----
"Poets have been mysteriously silent on the subject of cheese." --- G.
K Chesterton
___________
Jeff Boes  <><  jboes@qtm.net
Mur Consulting  http://murconsulting.hypermart.net/



==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe