P::RD and OOP
[email protected] Tue, 3 Aug 2004 14:22:13 +0200
| Newsgroups | perl.recdescent |
|---|---|
| Message-ID | <[email protected]> |
Hi,
I'm trying convert few parsing modules from the functional=20
style (with exported functions) to OO-style with the data
stored in a blessed hash. I'm doing it, because I hope that
the modules will be easier to use and maintain (for example
I will give many functions the same name and override them...)
The shortest module I've listed on the bottom, it is not very complex.
My problem is, that currently I use global variables to store
the parsed out data. For example the directories found in the
"component" rule below are stored into a hash referenced by
the global variable $Nokia::Gen::subref.
When I now move to objects and to a constructor like:
sub new {
my $proto =3D shift;
my $class =3D ref($proto) || $proto;
my $self =3D {};
$self->{_PARSER} =3D Parse::RecDescent->new(GRAMMAR) or die 'Bad =
grammar';
bless $self, $class;
}
Then where do I save those dirs? $Nokia::Gen::self->{SUBREF}=20
wouldn't work since there is no such variable. And if I use=20
$main::parser->{SUBREF} then the variable name is hardcoded.
Regards
Alex
PS. Here is one of my modules:
package Nokia::Gen;
use strict;
use vars qw($parser $comref $optref $subref $VERSION @ISA @EXPORT);
use Exporter();
use Parse::RecDescent;
#$::RD_WARN =3D 1;
#$::RD_HINT =3D 1;
#$::RD_TRACE =3D 120;
$VERSION =3D 1.0;
@ISA =3D qw(Exporter);
@EXPORT =3D qw(&parseGenfile);
use constant GRAMMAR =3D> q(
genfile: chunk(s) /^\Z/
chunk: comment | option | component | <error>
comment: /#([^\x0D\x0A]*)/ { =09
push @{$Nokia::Gen::comref}, $1;
}
option: /<OPTION\b/i /\w+/ optarg(?) '>' {
# for each option create an array holding optargs
push @{$Nokia::Gen::optref->{lc $item[2]}}, @{$item[-2]};
}=20
optarg: /\w+/
component: /\S+/ <skip: '[ \t]+'> dir {
# change backslahes to slashes
$item{dir} =3D~ s|\\\\+|/|g;
print STDERR "Warning: directory $item{dir} not found\n"
unless -d $item{dir};
print STDERR "Warning: directory $item{dir} listed multiple times\n"
if $Nokia::Gen::subref->{uc $item{dir}}++;
}
dir: /"([^"]*)"/ { $1 } | /\S+/
);
$parser =3D Parse::RecDescent->new(GRAMMAR) or die 'Bad grammar';
sub parseGenfile($$$$)
{
my $text =3D shift;
($comref, $optref, $subref) =3D @_;
defined $parser->genfile($text) or die 'Bad text';
}
1;