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

Hello All, I am trying to get my script to capture the entire line of my find (header piece) and not just the find characters (first two characters in $find). I have tried many variations and still come up with nothing that works. Any help would be great!

use strict; use warnings; my $find = '^(H0|HT)'; my $header; open (NEW, ">", "OUTPUTTEST.txt" ) or die "could not open:$!"; open (FILE, "<", "NEWFILETEST.txt") or die "could not open:$!"; while (<FILE>) { if (/($find)/) { $header = $1; } elsif (/^\s{38}\S*/) { print NEW "$header\t", $_; } } close (FILE); close (NEW)

input file

HT00000000 NOTE1 NOTE2 NOTE3

current output file

HT NOTE1 HT NOTE2 HT NOTE3

expected output file

HT00000000 NOTE1 HT00000000 NOTE2 HT00000000 NOTE3

Replies are listed 'Best First'.
Re: Caputre Entire Line Not Just Find
by kennethk (Abbot) on Jul 13, 2016 at 16:32 UTC
    If you want to grab everything via capture, you'll need to match everything:
    while (<FILE>) { if (/(.*$find.*)/) { $header = $1; } elsif (/^\s{38}\S*/) { print NEW "$header\t", $_; } }
    Note that . matches every character but a newline, so there's no need to worry about chomping. See s in Modifiers in perlre.

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      Thank you kennethk, this is exactly what I was trying to accomplish. Truly appreciated.

Re: Caputre Entire Line Not Just Find
by Eily (Monsignor) on Jul 13, 2016 at 16:31 UTC

    while(<HANDLE>) sets the special variable $_ to the current line on each iteration (and /$find/ is applied on $_ by default. $str =~ /$find/ would apply it on $str). So $header = $_; should do what you need, although a chomp may be required.