longlines.pl 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #!/usr/bin/env perl -w
  2. use strict;
  3. my $filename = $ARGV[0];
  4. if (!$filename) {
  5. print "Usage: longlines.pl <filename> [length]\n";
  6. exit(1);
  7. }
  8. # Set a default maximum line length.
  9. my $max_length = $ARGV[1] || 80;
  10. my @lines = ();
  11. my $line_num = 0;
  12. open(HANDLE, "<", $filename) or die "Cannot open $filename\n";
  13. # Read the file and track the lines with length > $max_length.
  14. while (<HANDLE>) {
  15. $line_num++;
  16. # Subtract one because the newline doesn't count toward the
  17. # length.
  18. if (length($_) - 1 > $max_length) {
  19. push @lines, $line_num;
  20. }
  21. }
  22. # If more than five long lines were found, truncate to five and
  23. # indicate that others were present, too.
  24. if (@lines > 5) {
  25. @lines = @lines[0..4];
  26. push @lines, "and others";
  27. }
  28. # If any long lines were found, notify and exit(1); otherwise,
  29. # exit(0).
  30. if (@lines) {
  31. print $filename." (line".((@lines > 1) ? "s" : "")." ".
  32. join(", ", @lines)." exceed".((@lines == 1) ? "s" : "").
  33. " length $max_length)\n";
  34. exit(1);
  35. } else {
  36. exit(0);
  37. }