in reply to (jeffa) Re: when reading a file how to print a line one above the current line??
in thread when reading a file how to print a line one above the current line??

But why tell him to read a filename at all in the case? I find that if one is taking filenames on the commandline, it's much better to use the diamond operator and let perl decide whether I should be reading from a bunch of files or STDIN, which allows for more flexibility.

And some technical critique - you didn't guard your print $last. This is what I have in mind:
#!/usr/bin/perl use strict; use warnings; my $prevline; while (<>) { if(/ALARM:/) { print $. - 1, ": $prevline" if defined $prevline; print "$.: $_"; } $prevline = $_; }
____________
Makeshifts last the longest.

Replies are listed 'Best First'.
Re: Re^2: when reading a file how to print a line one above the current line??
by dsheroh (Monsignor) on Jun 04, 2002 at 17:10 UTC
    Good point, but, personally, I'd do it as
    my $prevline = ''; ... print $. - 1, ": $prevline";
    This way doesn't have the overhead of testing every time whether $prevline is defined. Or you could initialize it to "BOF\n" for a more explicit indication of what's going on.
      I thought about the efficiency issue, but I guess it boils down to personal choice. With the guarded print you don't get to see a -1:\n should the pattern happen to match on the first line, and really that single test does very little to performance. We could pull out Benchmark here but I suspect the difference would be within measurement jitter (how is this exactly called in English?) for any less than a few hundred thousand lines.

      Makeshifts last the longest.