JavaRed
JavaRed

Reputation: 708

Parse a line after a matching pattern in a file in a Perl script

Given a file in format:

Foo:
  var1 = 1
  var2 = 2
  var3 = 3
Bar: 
  var1 = 4
  var2 = 5
  var3 = 6
Baz:
  var1 = 7
  var2 = 8  
  var3 = 9

I would like to open this file, read it line by line and find occurence var3 which comes after pattern Baz and take the value 9 from it in a perl script. What is best regex to do this?

sub getValue {
    open($fh, $file);
    while(my $line = <$fh>) {
        chomp($line);
        if($line =~ "regex here" ) {
        my $value = $3;
        }
    }
    return $value;
}

So with correct regex, I expect this sub return value 9.

Upvotes: 0

Views: 576

Answers (1)

zdim
zdim

Reputation: 66964

Since you process line by line you need to keep the state, to know when inside Baz: section

my $in_sec;

while (<$fh>) 
{    
    if    (/^Baz:/)     { $in_sec = 1; }
    elsif (/(?<!Baz):/) { $in_sec = 0; }

    if ($in_sec) {
        my ($num) = /var3\s*=\s*(\d+)/;
        say $num if $num;
    }   
}

The flag is turned off when another section starts, detected by using a negative lookbehind.

Or, read the whole file into a scalar so that you can match across lines.

Please use lexical filehandles and the three-argument open, it's better.

Upvotes: 3

Related Questions