V. Tej V. Tej - 1 year ago 66
Perl Question

Find a word which is after a pattern and before another pattern using perl

I want to find a word in a file which is after a particular pattern and before a particular pattern.
Here is the content from the file:

print("Hi", "My name is", "Tej");

So, I want to get the word
alone and store it into an array. Similarly, I have many such files with similar pattern as above but with different names, so I want to push all those names into an array. i.e. I want the words from the from the files which are after the pattern
print("Hi", "My name is", "
and before the pattern

I wrote the script for opening files and passing the file handle to a function to search for the word which is after and before the pattern. The code for the function is as follows:

sub search{
my $file_handle = shift;
while (<$file_handle>)
/.print("Hi", "My name is", "[\s]+([A-Za-z_0-9]+)/ ;
push @array, $1;

I know the regex doesn't work but I am not sure about how to find the word I need. Any help provided is appreciated.

Answer Source

Here's how I would do it:

sub search {                                    
    my $file_handle = shift;
    while (<$file_handle>) {
        if (/print\("Hi", "My name is", "([^"]+)"\);/) {
            push @array, $1;

I escaped the special characters inside the regex (i.e. ( and ) in this case), and I used "([^"]+)" to match all the non quotes inside the quotes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download