Your skill will accomplish what the force of many cannot |
|
PerlMonks |
Tokenizing and qr// <=> /g interplayby skyknight (Hermit) |
on Apr 23, 2005 at 15:01 UTC ( [id://450720]=perlquestion: print w/replies, xml ) | Need Help?? |
skyknight has asked for the wisdom of the Perl Monks concerning the following question: I wish to tokenize a stream and I'm interested in understanding the qr// operator a bit better, in particular how one uses the /g modifier with it. I'm not so much interested in pointers to CPAN for modules to do this for me, though I would appreciate pointers on how tokenizing is done if I am going about it in a stupid way. Specifically, I want to read in a list of possible tokens, build a pattern on the fly to recognize them, and then rip through an input string iteratively, reporting the tokens found within it. I figured that the way to do this was to concatenate all the possible token descriptors with the regex alternation symbol (|), embed the whole thing in parentheses to do capture, get a regex for it using the qr// operator with the /g modifier, and then have a while loop in whose conditional clause I bind the regex to the token stream. So, pseudo-code something like this...
Alas, this seems not to work. Perl gripes "bareword found where operator expected" where I try to put the /g modifier. I wondered if I had botched the syntax, so I tried the /i modifier, and that works, so no, apparently it just doesn't like having the /g modifier stuck on the qr// operator. Hm... So, I changed the while loop to this...
That works just fine, but I'm left wondering what exactly Perl is doing when I write my code thusly. Namely, I'm wondering if it is any better than doing this...
I want to build this tokenizer pattern only once, and I'm concerned that the ways I've hacked around qr//'s apparent refusal to allow a /g modifier doesn't accomplish this. Namely, I'm worrying that the pattern is getting recompiled every time I use it since I'm embedding it in a new //. So, what's the deal? Why won't qr// take /g? Is this a bug, a feature, or just a complete lack of comprehension on my part? I'm rather confused.
Back to
Seekers of Perl Wisdom
|
|