in reply to Re^2: counting lines in perl
in thread counting lines in perl
Try some <code> tags.
That should help. I'm not sure why you're using English. You should use strict. You always have a count of at least one - not zero. What we're doing now is checking - if the lines match, increment the count. If they don't match, print out the last match, and then reset. Finally, when we're done, we'll print out the last line.#!/usr/bin/perl # uniq.pl: remove repeated lines. use strict; use diagnostics; $oldline = ""; $n = 1; while ($line = <>) { if ($line eq $oldline) { #$n = $n + 1; $n++; } elsif ($oldline) { print " $n $oldline"; $n = 1; $oldline = $line; } } if ($oldline) { print " $n $line"; }
Hope that helps.
(Warning - untested.)
Update: Of course, being untested, crashtest points out an obvious error... had $line when it should be $oldline.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: counting lines in perl
by crashtest (Curate) on Feb 26, 2005 at 21:12 UTC | |
by imhotep (Novice) on Feb 26, 2005 at 22:24 UTC | |
by crashtest (Curate) on Feb 26, 2005 at 23:09 UTC | |
by imhotep (Novice) on Feb 26, 2005 at 23:57 UTC |