in reply to Re^6: Help editing a file based off seach criteria
in thread Help editing a file based off seach criteria

In your program you posted above, where did you use pos?

Also, the pos function does not do what you might think what it does.

Replies are listed 'Best First'.
Re^8: Help editing a file based off seach criteria
by perlnewb123 (Sexton) on Jan 13, 2009 at 17:26 UTC
    You're right, using pos is only giving me the previous line number if I feed it $. Not sure how I would go about placing data to that line number. Any suggestions on a better route to take?
    #!/usr/bin/perl open DATA, "</home/file.conf"; while (<DATA>) { if(m/\END\b/) { print "$.\n"; print "$_\n"; $pos = $.; $pos--; print "$pos\n"; } } close(DATA);
    produces: Line #, Data, Previous Line #

      That's a first step in the right direction. Now, you don't want to print the line number of the previous line, but the content of the previous line. So you will need to come up with some way to remember the previous line and output it when the current line matches /^END$/ (I note you wrote /\END\b/, but I assume that's not what you mean). As I outlined several replies before this one, one possible approach could be:

      1. Check the current line
      2. If it matches /END/, print the previous line (as remembered)
      3. Remember the current line as "previous line" in a variable
        This is ghetto, but it works... since I now know the line where I need to edit, how would I then edit the file and input data at that specific line?
        #!/usr/bin/perl open DATA, "</home/file.conf"; while (<DATA>) { if(m/\END\b/) { print "$.\n"; print "$_\n"; $pos = $.; $pos--; chomp $pos; $DESIRED_LINE_NUMBER = $pos; } } $. = 0; do { $LINE = <DATA> } until $. == $DESIRED_LINE_NUMBER || eof; print $LINE;