in reply to Re^2: How to print the lines immediately above and below a matching line?
in thread How to print the lines immediately above and below a matching line?

Then you need to change your code. Something like:
my $data = <DATA>; chomp $data; if ($this_line =~ /\Q$data/)
  • Comment on Re^3: How to print the lines immediately above and below a matching line?
  • Download Code

Replies are listed 'Best First'.
Re^4: How to print the lines immediately above and below a matching line?
by Bio90 (Initiate) on Nov 25, 2012 at 13:55 UTC
    I have tried that but it has returned a "Use of uninitialised value $data". I do not understand - surely $data is initialised by my $data = <DATA>;?

      Show that code? Where did you add the line?

        Here is the code with the change
        use strict; use warnings; open( my $fh, '<', 'input.txt') or die "Error opening file - $!\n"; open OUT, ">", "output.txt" or die "could not open output.txt $! \n"; my $this_line = ""; my $do_next = 0; my $data = <DATA>; while(<$fh>) { my $last_line = $this_line; $this_line = $_; chomp $data; if ($this_line =~ /\Q$data/) { print OUT $last_line unless $do_next; print OUT $this_line; $do_next = 1; } else { print OUT $this_line if $do_next; $last_line = ""; $do_next = 0; } } close ($fh); __DATA__ 4386_7#8 4350_7#6 4414_1#6