I would like to print specific data after matching a pattern or line. I have a file like this:
#******************************
List : car
Design: S
while (<FILE>) { #read line by line
if ($_ =~ /^Car/) { #if the line starts with 'Car'
<FILE> or die "Bad car file format"; #read the first line after a Car line, which is '---', in order to get to the next line
my $model = <FILE>; #assign the second line after Car to $model, this is the line we're interested in.
$model =~ /^([^\s]+)\s+([^\s]+)/; #no need for if, assuming correct file format #capture the first two words. You can replace [^\s] with \w, but I prefer the first option.
print "$1 $2\n";
}
}
Or if you prefer a more compact solution:
while (<FILE>) {
if ($_ =~ /^Car/) {
<FILE> or die "Bad car file format";
print join(" ",(<FILE> =~ /(\w+)\s+(\w+)/))."\n";
}
}