You still can't PreCompile that. You're forcing the calling script to parse the parser's grammar, generate the parser code and compile the parser code everytime it runs. That's extremely slow, so that's something you only want to do when the grammar is changed.

To achieve that goal, start by making make_grammar.pl as follows:

use strict; use warnings; use Parse::RecDescent (); my $szGrammar = <<'__END_OF_GRAMMAR__'; { use strict; use warnings; use constant DEBUG => 1; use Data::Dumper; sub AddToHash { print "MyParser->AddToHash(@_)\n" if (DEBUG); my ($this, $szVar, $szValue) = @_; $this->{Result}->{$szVar} = $szValue; } sub GetResult { print "MyParser->GetResult(@_)\n" if (DEBUG); my ($this) = @_; return $this->{Result}; } sub DumpResult { print "MyParser->DumpResult(@_)\n" if (DEBUG); my ($this) = @_; print Dumper($this->{Result}); } } test: expr(s) /^\Z/ expr: name '=' /\d+/ { $thisparser->AddToHash($item{name}, $item[-1]); } name: /\w+/ __END_OF_GRAMMAR__ Parse::RecDescent->PreCompile($szGrammar, 'MyParser') or die("Bad Grammar\n");

You run the above once, then you use it as follows:

use strict; use warnings; use MyParser (); my $hParser = MyParser->new(); my $szCode = "x = 1\ny = 2\nz = 3"; $hParser->test($szCode) or die("Bad code\n"); $hParser->DumpResult();

I still stand by my earlier note: I prefer the solution I posted earlier because it doesn't break if backtracking occurs like this one does.

I'd also like to add that <<'__END_OF_GRAMMAR__' ... __END_OF_GRAMMAR__ has fewer issues than q{ ... }.


In reply to Re^4: How do I return a hash from Parse::RecDescent? by ikegami
in thread How do I return a hash from Parse::RecDescent? by GrandFather

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.