I am a beginner in perl. I have a text file with text similar to as below. i need to extract VALUE="<NEEDED VALUE>". Say for SPINACH, i should be getting SALAD alone.
How to use perl regex to get the value. i need to parse multiple lines to get it. ie between each #ifonly --- #endifonly
$cat check.txt
while (<$file>)
{
if (m/#ifonly .+ SPINACH .+ VALUE=(")([\w]*)(") .+ #endifonly/g)
{
my $chosen = $2;
}
}
#ifonly APPLE CARROT SPINACH
VALUE="SALAD" REQUIRED="yes"
QW RETEWRT OIOUR
#endifonly
#ifonly APPLE MANGO ORANGE CARROT
VALUE="JUICE" REQUIRED="yes"
as df fg
#endifonly
use strict;
use warnings;
use 5.010;
while (<DATA>) {
my $rc = /#ifonly .+ SPINACH/ .. (my ($value) = /VALUE="([^"]*)"/);
next unless $rc =~ /E0$/;
say $value;
}
__DATA__
#ifonly APPLE CARROT SPINACH
VALUE="SALAD" REQUIRED="yes"
QW RETEWRT OIOUR
#endifonly
#ifonly APPLE MANGO ORANGE CARROT
VALUE="JUICE" REQUIRED="yes"
as df fg
#endifonly
This uses a small trick described by brian d foy here. As the link describes, it uses the scalar range operator / flipflop.