Perl keywords parsing

340 views Asked by At

Am currently writing a script in perl to parse the perl modules and fetch meaningful words from them. (other than perl keywords).

I have a rejection list array which contains the perl keywords. I use this to separate the meaningful words from the perl keywords.

my $pattern = join("|", @rejectionlist);
foreach my $word (@words) {
    if (!($word =~ /^$pattern$/i)) {
            push @meaningfulwords, $word;
    }
}

Is it possible to dynamically generate the perl keywords (rejection list array - by using any routines) ?

3

There are 3 answers

2
Ωmega On

If you really want to use regex for this kind of task, you should escape each keyword before you joint them into list. Insert \Q at the beginning of the keyword and \E at the end of the keyword.

my $pattern = '(?:\Q' . join('\E|\Q', @rejectionlist) . '\E)';
0
mpapec On
use B::Keywords qw( @Symbols @Barewords );

my %kw;
@kw{( map fc, @Symbols, @Barewords )} = ();

my @meaningfulwords = grep { !exists $kw{ fc($_) } } @words;
0
Borodin On

I suggest you take a look at the B::Keywords module. It categorizes all the reserved Perl identifiers into ten different categories, and exports ten corresponding arrays of names that you can use as you wish.

By the way your regular expression is wrong. You want /^(?:$pattern)$/ instead.