1

I am looking for a keyword in a multiline input using a regex like this,

if($input =~ /line/mi)
{
    # further processing
}

The data in the input variable could be like this,

this is
multi line text
to be matched
using perl

The code works and matches the keyword line correctly. However, I would also like to obtain the line where the pattern was matched - "multi line text" - and store it into a variable for further processing. How do I go about this?

Thanks for the help.

1
  • my @match = grep /line/mi, split /\n/, $input perhaps? Although the /m modifier is completely useless in that regex. Commented Aug 12, 2013 at 10:09

4 Answers 4

3

You can grep out the lines into an array, which will then also serve as your conditional:

my @match = grep /line/mi, split /\n/, $input;
if (@match) {
    # ... processing
}
Sign up to request clarification or add additional context in comments.

1 Comment

You should remove the /m that has no effect here, since there are no instances of ^ or $.
0

TLP's answer is better but you can do:

if ($input =~ /([^\n]+line[^\n]+)/i) {
    $line = $1;
}

Comments

0

I'd look if the match is in the multiline-String and in case it is, split it into lines and then look for the correct index number (starting with 0!):

#!/usr/bin/perl

use strict;
use warnings;

my $data=<<END;
this is line
multi line text
to be matched
using perl
END

if ($data =~ /line/mi){
    my @lines = split(/\r?\n/,$data);
    for (0..$#lines){
        if ($lines[$_] =~ /line/){
            print "LineNr of Match: " . $_ . "\n";
        }
    }
}

Comments

0

Did you try his? This works for me. $1 represents the capture of regex inside ( and ) Provided there is only one match in one of the lines.If there are matches in multiple lines, then only the first one will be captured.

if($var=~/(.*line.*)/)
{
print $1
}

If you want to capture all the lines which has the string line then use below:

my @a;
push @a,$var=~m/(.*line.*)/g;
print "@a";

3 Comments

What if I'm passing arguments to my perl script - will this work correctly in that case?
and what is the argument that you are passing?
Never mind that, I was confused between argument syntax for shell script and perl. Since $1 denotes the first argument to a shell script, I mixed it up with the perl for the same, and thought it would lead to printing of the argument value instead of the regex output :-)

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.