in reply to How do I parse and evaluate a file line-by-line?

Here's one quick solution:
#!/usr/bin/perl -w use strict; my $last = ""; my $cursor = -1; my @output; while (<DATA>) { my ($time, $switch) = split "\t"; if ($switch eq $last) { $output[$cursor] = $_; } else { $cursor++; $output[$cursor] = $_; $last = $switch; } } foreach (@output) { print; } __DATA__ time1 UP time2 DOWN time3 UP time4 DOWN time5 DOWN time6 DOWN time7 UP time8 UP time9 UP time10 DOWN time11 UP
The idea here is to record just the last "UP" or "DOWN" event in a string of one or more "UP" or "DOWN" events. $cursor is used to keep our place in the array, overwritting successive UP's and DOWN's as necessary.

Gary Blackburn
Trained Killer

Replies are listed 'Best First'.
Re: Re: How do I parse and evaluate a file line-by-line?
by merlyn (Sage) on Mar 03, 2001 at 20:47 UTC
    You can tighten that middle loop up a bit by getting out of "C think" and getting into "Perl think":
    while (<DATA>) { my ($time, $switch) = split "\t"; if ($switch eq $last) { $output[-1] = $_; } else { push @output, $_; $last = $switch; } }
    The $cursor variable is unnecessary, because Perl always knows how long the array is.

    -- Randal L. Schwartz, Perl hacker

      Thanks for that... I rarely use $array[$element] to grow an array, preferring "push", but I couldn't use push indiscriminately here because I needed to write over successive instances of UP or DOWN. Of course, $array[-1] was exactly what I was looking for. Gotta get used to using the relative position in an array....

      And for the record, it wasn't "C think" as I actually know absolutely nothing about C. It was just inexperience. :-D

      Gary Blackburn
      Trained Killer