JonDepp has asked for the wisdom of the Perl Monks concerning the following question:

Hello all,

I have been looking at this for a few days and cannot see an answer so I humbly ask your opinion.

I have a data file that is laid out like the following:

DOE JOHN 123 DENIRO ROBERT 123 123 123 CUBE ICE 123 123

There are names followed by lines that have numbers in them that correspond to each name. The name line can be followed by any number of number lines. I want to extract the name and its corersponding number lines if the name matches and/or the number lines match some user input.

The following code is where I am starting:

use strict; use warnings; open OUTPUT, "> info.txt" or die $!; print "What file do you want parsed? "; my $file1 = <STDIN>; print "Name: "; chomp (my $name = <STDIN>); open FILE, "$file1"; while (<FILE>) { if (/$name/.../\n/) { print OUTPUT $_ until ($_ ne\d+/); } }

I would be most grateful for any guidance. Thanks!

Replies are listed 'Best First'.
Re: Extract lines from text file
by toolic (Bishop) on Jan 31, 2011 at 19:51 UTC
    Use a state variable.
    use warnings; use strict; my $input_name = 'DENIRO ROBERT'; my $print_flag = 0; while (<DATA>) { chomp; if (/^[a-z]/i) { $print_flag = ($_ eq $input_name) } print "$_\n" if $print_flag; } __DATA__ DOE JOHN 123 DENIRO ROBERT 123 123 123 CUBE ICE 123 123
    prints:
    DENIRO ROBERT 123 123 123
Re: Extract lines from text file
by jethro (Monsignor) on Jan 31, 2011 at 22:48 UTC
    if you also want to search for a number, just change toolics code to collect name and numbers in an array. Reset that array whenever you see the next name. Also have a variable $found that you set to 1 if you find the name or number and set to 0 whenever you see the next name. But first when you find the next name and $found is 1, print out the data you collected in the array.