After a quick search, I found this very useful post made here some 3 years ago.

read lines... wait, back up?

Basically what I want to do is go line by line through my file, if I hit a specific string, take the next few lines, looking for another string. If I find the 2nd string, I'll need to check the next 10 lines or so for another string, then go BACK 1 line ahead of where I matched my first string, and start the whole process again. I've gotten up to matching the first two strings, but my SEEK always goes back to the first of the file.

It looks to me that $. doesn't give the real line number, but just counts how many lines Perl has run through. Anyways, any help is appreciated.

#!/usr/bin/perl # # use strict; use warnings; my $file = "file.log"; open ( IN, $file ) || die "Can't open $file $!"; my %position; while ( <IN> ) { chomp; $position{$.+1} = tell(IN); #I don't quite grasp this part yet # $. holds line number if ( /first_string/ ) { my $count = 0; #bad way of only finding 2nd string once print "$. $_\n"; seek IN, $position{$.+1}, 0; while ( <IN> ) { chomp; if ( ( $_ =~ /2nd_string/ ) && ( $count < 1 ) ) { print "found 2nd string\n"; $count += 1; } } } seek IN, $position{$.+1}, 0; } close FILE;
Since I can't print out $position{$.+1} I can't tell if it's seeking properly - ever. But, only the the last seek at the bottom of the file is giving me an 'unitialized value'.

Edited by castaway - changed literal html link text to an id:// link


In reply to Problem with SEEK to go back/forward a few lines. by GaijinPunch

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.