Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to access a variable from the grammar code

10 views
Skip to first unread message

Yuri Shtil

unread,
Jan 10, 2012, 11:54:56 AM1/10/12
to recde...@perl.org
I use OO perl and created a class that uses recdecent.
I want to access method variables from the grammar actions. Is there an elegant way to pass a parameter to the Parse::RecDescent constructor and access it from the actions?

I used an awkward construct and I don't like it:

-----

Package Foo;

our $var;

...
my $grammar = '...
# Capture the object instance
my $object = Foo::$var;
startrule: a b c {$object->method}'

...

sub action {
# Capture $var
$var = SOmeClass->new();
# $var is used in grammar
my $parser = Parse::RecDescent ($grammar);
$parser->startrule(SomeText);
}


Also I think this would not work with Precompile.

-----------------------------------------------------------------------------------
This email message is for the sole use of the intended recipient(s) and may contain
confidential information. Any unauthorized review, use, disclosure or distribution
is prohibited. If you are not the intended recipient, please contact the sender by
reply email and destroy all copies of the original message.
-----------------------------------------------------------------------------------

Damian Conway

unread,
Jan 10, 2012, 4:50:16 PM1/10/12
to Yuri Shtil, recde...@perl.org
On 11 January 2012 03:54, Yuri Shtil <ysh...@nvidia.com> asked:

> Is there an elegant way to pass a parameter to the Parse::RecDescent
> constructor and access it from the actions?

I'm afraid there isn't.

The best workaround is probably to make the shared resource an attribute
of the parser object (instead of using an external variable) and then
access it within the grammar via $thisparser. Like so:

my $grammar = q{
startrule: a b c {$thisparser->{sc_obj}->method}
...
};

sub action {
my $parser = Parse::RecDescent->new($grammar);
$parser->{sc_obj} = SomeClass->new();
$parser->startrule($sometext);
}


Damian
0 new messages