develooper Front page | perl.beginners | Postings from February 2009

Re: Add Line break when first of a line changes

Thread Previous | Thread Next
From:
Telemachus
Date:
February 15, 2009 08:24
Subject:
Re: Add Line break when first of a line changes
Message ID:
20090215162341.GA5319@ilium
On Sun Feb 15 2009 @  9:48, Jack Butchie wrote:
> I used a tab, then a pipe, both produced the same results.
>
> LAWNS|123|GOOD
>
> LAWNS|12|GOOD

The results are the same because the test is for the whole line. If you
only want to test one field, you need a different script. For example, this
will test the first field (only) of each line:

    #!/usr/bin/perl -w

    my $file = shift @ARGV;

    open IN, $file or die "Couldn't open $file: $!";
    my $before;

    while (my $line = <IN>) {
      my $now = (split /\|/, $line)[0];
      if ($before and $before ne $now) {
        print "\n";
      }
      print $line;
      $before = $now;
    }

    close IN;

On the other hand, this is getting more and more hacked together, as you
can see. The big problem remains that you are going to have a script that
you can't maintain because you don't know how it works.

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About