0

I'm attempting to find certain keywords inside a perl script. For some reason my Regex wont find keywords followed by a ; and I believe \n

For example if I was searching for the word "print" the below code would find print if the string contained

print ;

but wouldn't if it was

print;

My current code:

$keyword = "print";
if($string =~/\b$keyword\b/g)
{
    print "found";
}
1
  • Not a good idea at all. May be PPI can be useful, never used though! Commented Apr 16, 2014 at 7:43

3 Answers 3

4

use PPI for parsing perl code:

use strict;
use warnings;

use PPI;

my $src = do {local $/; <DATA>};

# Load a document
my $doc = PPI::Document->new( \$src );

# Find all the barewords within the doc
my $words = $doc->find( 'PPI::Token::Word' );
for (@$words) {
    print $_->content, "\n";
}

__DATA__
$keyword = "print";
if ($string =~/\b$keyword\b/g)
{
    print "found";
}

outputs:

if
print
Sign up to request clarification or add additional context in comments.

2 Comments

Great solution! but is there no way of simply tailoring my Regex to find any kind of word even when they're next to ;? To be honest I'm still surprised \b didn't work, or the below two answers.
It is not possible to help you anymore with your question as you have it written. You do not include an actual working example of what is failing for you. You say you have a string that contains the word print, but are not able to match it. Then edit your post so that you actually define that string and attempt to match against it, then you will get better assistance: How do I ask a good question?
0
if ($keyword =~ m/\bprint\b\s?;?/sim) {
    # Successful match
} else {
    # Match attempt failed
}

1 Comment

No luck unfortunately
0

You may need to quote your variable. use \Q and \E in the regex. eg /\Q$var\E/g

UPDATE: this worked

#!/usr/bin/perl -w
use strict;
use warnings;

my $keyword = "print";
my $string = 'print;';
if($string =~/\b$keyword\b/g)
{
    print "found";
}

1 Comment

see my update. can you tell us how your assigning the variables?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.