in reply to Search for a string in a file and get the string in the next line

TMTOWTDI. This example has embedded data, to read from a file then replace DATA with a file handle, see open to open a file and obtain the filehandle:
use warnings; use strict; while(<DATA>) { if (/PSP-Ri/) { $_ = <DATA>; # Grab the text after '--' my $pairs = (split('--'))[1]; # Remove that pesky (0x1) $pairs =~ s/\(.*?\)//; # Create a hash from (key<spaces>value) my %hash = split(/\s+/,$pairs); # Print the hash while (my($k,$v) = each(%hash)) { print "$k = $v\n" } } } __DATA__ 125 09082010 093627.953624:1.01.00.27144.Info .CC: *GCID:0x00000013--I +ngress PSP-Ri 206 09082010 093627.953812:1.01.00.27145.Info .CC: *GCID:0x00000013--C +odec G711 (0x1) pktSize 20 attrib 0x1c00
  • Comment on Re: Search for a string in a file and get the string in the next line
  • Download Code

Replies are listed 'Best First'.
Re^2: Search for a string in a file and get the string in the next line
by moritz (Cardinal) on Oct 11, 2010 at 12:16 UTC
    There are two problems with reading from the file handle inside the while loop:
    1. To get robust code, you have to check if you're at the end of the file while reading from the file
    2. If you have two matching lines in a row, and both the second and the following line to be printed, you have to take special precautions

    Which is why I generally prefer the approach of using a flag

    use strict; use warnings; my $flag = 0; while (<DATA>) { if ($flag) { # print parts of $_ as necessary } $flag = /Ingress PSP/; }
    Perl 6 - links to (nearly) everything that is Perl 6.