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...
my $stream = 't1 t2 t1 t3 t1 t4'; my @tokens = ('t1, 't2', 't3', 't4'); my $pattern = join('|', @tokens); my $regex = qr/($pattern)/g; while ($stream =~ $regex) { print "token: $1\n"; }
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...
while ($stream =~ /$regex/g) { print "token: $1\n"; }
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...
while ($stream =~ /($pattern)/g) { print "token: $1\n"; }
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.
In reply to Tokenizing and qr// <=> /g interplay by skyknight
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |