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

Hi Monks,

I want to know the previous line of the file while processing it in current line in while loop. For example see the below code

my $file = 'input.txt'; open STDLOG, "$file" or die("$file file cannot be opened: $!\n"); while (defined(my $row = <STDLOG>)) { chomp $row; print "Current line is: $row \n"; # here i want to print the previous line }


Note: Input file is not stored in array, since it is big file.

Thanks in advance
Shanmugam A.
  • Comment on How to get previous line of the file while processing current line in while loop
  • Download Code

Replies are listed 'Best First'.
Re: How to get previous line of the file while processing current line in while loop
by Nikhil Jain (Monk) on Mar 29, 2011 at 07:37 UTC
    use strict; use warnings; open(my $fh, '<', "$file") or die $!;#use three argument open my $previous_line = q{}; #initially previous line would be empty while(my $current_line = <$fh>){ chomp; print"$current_line\n"; print"$previous_line\n"; #assign current line into previous line before it go to next line $previous_line = $current_line; } close($fh);
Re: How to get previous line of the file while processing current line in while loop
by JavaFan (Canon) on Mar 29, 2011 at 09:17 UTC
    Your question is "how do I implement a single element buffer"? It's easy:
    my $previous = <STDLOG>; while (my $current = <STDLOG>) { print "Current line is: $current"; print "Previous line is $previous"; $previous = $current; }
Re: How to get previous line of the file while processing current line in while loop
by Anonymous Monk on Mar 29, 2011 at 15:01 UTC

    Possible heresy

    If its just for a trivial *nix sysadmin task, you could do worse than man grep and check out some options including -A