How to use B::Hooks to manipulate the perl parser
Asked Answered
P

1

15

I'm looking to play with perl parser manipulation. It looks like the various B::Hooks modules are what people use. I was wondering:

  1. Best place to start for someone who has no XS experience (yet). Any relevant blog posts?

  2. How much work would be involved in creating a new operator, for example:

    $a~>one~>two~>three

~> would work like -> but it would not try to call on undef and would instead simply return undef to LHS.

Although a source filter would work -- I'm more interested in seeing how you can manipulate the parser at a deeper level.

Parmesan answered 23/5, 2015 at 15:25 Comment(8)
That sounds like an interesting feature. :)Echelon
I thought of it while getting annoyed doing if( $dom->at('div')->at('h1')) { in Mojo::DOM and getting can't call undefined becasue div didn't exist :)Parmesan
I have not figured this out yet but this looks promising: metacpan.org/pod/B::UtilsParmesan
Have you considered using autobox? A very simple package with a fundamental AUTOLOAD routine would suffice. You wouldn't have a new operator, but adding all possible methods there are to undef. This would probably have terrible performance impacts. Like this: use autobox UNDEF => 'SilentUndef'; … your code… package SilentUndef; sub AUTOLOAD {sub{}}.Idealism
Thanks I hadn't seen autobox before. That looks like a good solution. Wouldn't it not be too bad performance wise because you are only 'autoboxing' undef (which shouldn't be called on anyway). But right now I'm actually just trying to learn about the parser. The "tentatively call" thing above that avoids undef was just an example. BTW I now think I have to use: metacpan.org/pod/B::Hooks::OP::Check.Parmesan
I never spent the time to figure out how to use B::Hooks to do this in perl5. I ended up doing it in perl6: Slang::Dotty. In perl6 you can actually change the the syntax at runtime arbitrarily. Which is called a "slang".Parmesan
When I did some XS in the past (which I completely forgot at this point) I started from perldoc.perl.org/perlxstut.html For adding new operators, I would probably start from perldoc.perl.org/perlguts.html#Custom-OperatorsTrowbridge
@Trowbridge That looks exactly what I need. I'd say using B::Hooks::OP::Check and hooking the custom operator OP would be the place to start. I won't be able to test this theory for a month or so.Parmesan
I
1

I don't believe you can add infix operators (operators whose operands are before and after the operator), much less symbolic ones (as opposed to named operators), but you could write an an op checker that replaces method calls. This means you could cause ->foo to behave differently. By writing your module as a pragma, you could limit the effect of your module to a lexical scope (e.g. { use mypragma; ...}).

Incuse answered 29/10, 2015 at 18:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.