Phoenix.pm: Parameter parser
Doug Miles
doug.miles at bpxinternet.com
Tue Nov 26 15:46:10 CST 2002
Doug Miles wrote:
> Hey all,
>
> I just implemented a parser that takes something like this:
>
> command param1 param2="value2" param3="value3 \"foo\""
>
> and puts the parameters and values into a hash. The value for param1
> would be "1". I'm not sure I implemented it the best way, though. I
> thought I'd get some ideas from you folks to get a different
> perspective. I'll post what I did after I get some responses. I don't
> want to contaminate your thinking. :)
>
>
I left out a few details that I forgot to mention. There can be
optional whitespace around the '=' and command may be a command, a
scalar, an array, or a method call. What the program does from there
depends on which it is. Right now the program is putting the data in an
array, but this will change to a hash in the future. Oh, and ignore the
$tag_parser parameter. :)
I have to pay around with Scott and Eden's examples some more, but here
is what I did (I'm sure the formatting will be screwed up):
#!/usr/bin/perl
use Regexp::Common;
my $tag_content = '$scalar param1 param2="\"test2\""';
my @parameters = process_tags('', $tag_content);
print join('|', @parameters) . "\n";
$tag_content = q{@array format="'test3'" default_format="test4"};
@parameters = process_tags('', $tag_content);
print join('|', @parameters) . "\n";
$tag_content = 'command doug="test5" julie="test6"';
@parameters = process_tags('', $tag_content);
print join('|', @parameters) . "\n";
# process_tags #########################################################
sub process_tags
{
my $tag_parser = shift;
my $tag_content = shift;
# Suppress "Use of uninitialized value in" warnings.
pos($tag_content) = 0;
my @parameters;
while(pos($tag_content) < length($tag_content))
{
if(my ($match, $scalar) = $tag_content =~ /\G^(\$([a-zA-Z0-9_:.]+))/)
{
pos($tag_content) += length($match);
}
elsif(my ($match, $array) = $tag_content =~ /\G^(\@([a-zA-Z0-9_:.]+))/)
{
pos($tag_content) += length($match);
}
elsif(my ($command) = $tag_content =~ /\G^([a-zA-Z0-9_:.]+)/)
{
pos($tag_content) += length($command);
}
elsif($tag_content =~
/
\G # Start at
last match pos.
(([a-zA-Z0-9_:.]+) # A parameter.
(?:\s*?=\s*? # '=' &
optional WS.
$RE{delimited}{-delim=>'"'}{-esc=>'\\'}{-keep})?) # '"'
delimited value.
/x # / Fix VIM syntax highlighting problem.
)
{
my $match = $1;
my $parameter = $2;
my $value = defined($5) ? $5 : 1;
$value =~ s/\\"/"/g;
#print "$1|$2|$3|$4|$5|$6|$7|$8|$9\n";
push(@parameters, ($parameter, $value));
pos($tag_content) += length($match);
}
else
{
pos($tag_content) += 1;
}
} # END: while(pos($tag_content) < length($tag_content))
More information about the Phoenix-pm
mailing list