-3

How do I find out linecount in perl similar to what wc -l gives me. A method preferably that doesn't require reading the whole file.

vatsal
  • 109
  • 2
  • 12
  • The *best* way to do it would depend on what you're already doing with the file and when you need the info, but you haven't shared that info. – zzxyz Sep 24 '18 at 20:49

1 Answers1

0

This question is way too broad and un-specific. But as it is based on an often seen misconception I'd like to comment on that.

A file is a sequence of bytes with no notion of "lines." The lines that we see when a file is displayed are determined by a particular character (or a short sequence of characters) in the file, denoting a "linebreak" to be used by software that views or edits the file. They are not a property of a file that one can just look up as metadata.

So you have to read the whole file in order to determine how many "lines" it has.

This can be done using native tools in a language or by running an external utility which does this, like wc. I'd recommended to do it using Perl in a Perl program, since the job fits squarely within Perl's most common uses. Then there are a number of ways to do this but we'd need to see your code in order to offer a specific recommendation.

zdim
  • 64,580
  • 5
  • 52
  • 81
  • @Abigail By: Why go out system-shopping for something that's squarely in the language's capability? There are systemic benefits from staying home (so to speak), while there are very few benefits from going out; it barely saves a line or two of code -- if any -- as we must check etc. I think computing, and major languages, have evolved so much that the "glue" aspect of Perl isn't front and center anymore; i take it more to be a complete language that can work out most that's needed. But perhaps I went a bit to far and so I edited that away, thank you for calling it. – zdim Sep 26 '18 at 18:24
  • @Abigail Well, that's a valid argument. But by it all program's should then be choke full of various external utilities, no? It increases dependency on external code a lot. By "rolling my own" (three lines) I avoid going out to sea, to the system that is. I don't need "existing code" for such simple stuff (but I don't see it as bad if people use it, and I used to do it a lot). – zdim Sep 26 '18 at 18:37
  • @Abigail Thinking about it, yes, I refuse to "use existing code" (external utilities) _for very simple stuff_. I won't load a module or go out to system for a single job that's done fully in two or three lines of code. Now I am responding to your comment of principle; I don't object to `wc` or similar system tools. – zdim Sep 26 '18 at 18:40