I needed to reformat a bunch of Perl code, so I began writing this
as an exercise to try and learn regular expressions better, but I've
gotten stuck and I'm not sure why.
It's a very light weight perl parser that handles just a subset of perl.
Here's the code:
#!/usr/bin/perl -w
use strict;
my $bareword = qr/(\w+)/;
my $quotelike = qr/((['"]).+?\2)/;
my $subscript = qr/([\[{]\w+[\]\}])/;
my $variable = qr/(\$\w+($subscript)*)/;
my $sub_arg = qr/($quotelike|$variable|$bareword)/;
my $sub_args = qr/($sub_arg,)*($sub_arg)/;
my $subroutine = qr/((\w+::)*\w+\($sub_args)/;
while (<>) {
my @args = ();
my @labels = ();
my ($spacer, $obj, $method) = m/^(\s+)(\$\w+->)(\w+)\(/gc;
LOOP: {
push(@args, $1), redo LOOP if m/\G$quotelike,?\s*/gc;
push(@args, $1), redo LOOP if m/\G$variable,?\s*/gc;
push(@args, $1), redo LOOP if m/\G$subroutine,?\s*/gc;
push(@args, $1), redo LOOP if m/\G$bareword,?\s*/gc;
}
@labels = ($method eq "hidden") ? qw(name value) :
##integer, text
qw(name label value maxlength ex
+tras subtext size uiLevel defaultValue hoverHelp)
;
print join '', $spacer, $obj, $method, "(\n";
for(my $index=0; $index < @args; ++$index) {
print join '', "\t\t-", $labels[$index], ' => ', $args[$index]
+, ",\n";
}
print join '', $spacer, ");\n";
}
This is the line I'm trying to parse:
$f->readOnly($session{form}{cid},WebGUI::International::get(469,"W
+ebGUIProfile"));
And this is the formatted output, incorrect:
$f->readOnly(
-name => $session{form}{cid},
-label => WebGUI::International::get(469,
-value => "WebGUIProfile",
);
The $sub_args regex is only matching the second set of parentheses, and I have
no idea why. Can anyone clue me in?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.