[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

Re: Finding & printing the longest line - thanks



"Pete Peterson" <petersonp genrad com> wrote:

OK -- if there *IS* a longest line and you're not determined to use
wc -L and regexps, you could instead do:
perl -ne '$max = length($long = $_) if length($_) >$max; END{print $long}' file


If two lines have the same length, this would print the first of them.  If
you changed the condition to ">=", it would print the second of them.
Printing all the lines with the max length would be a bit trickier,
but not difficult -- you'd need both an equality test and a greater-than
test.  ... something like this:
--------------------
#!/usr/bin/env perl
while (<>) {
  if (($len = length($_)) > $lmax) {
    $lmax = $len;
    @longest =($_);
  }
  elsif ($len == $lmax) {
    push(@longest, $_);
  }
}
print @longest;
--------------------

Note that this scheme makes only one pass through the file in either case.

I'll probably just go the wc / egrep route for now, but I'll save this for future reference when I learn a bit more about perl.


Thanks!


Eric Sisler Library Computer Technician Westminster Public Library Westminster, CO, USA esisler westminster lib co us

Linux - don't fear the Penguin.
Want to know what we use Linux for?
Visit http://gromit.westminster.lib.co.us/linux





[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]