in reply to Re^2: system command
in thread system command

But actually I want to find the total number of lines without opening the file

Impossible. Actually, using system or backticks, you are creating a new process and opening more files than you would just using Perl.

Update: But if you insist on forking, how about

sub line_count { my ($fname) = @_; open(my $pipe, '-|', 'cat', $fname) or die("Unable to launch cat: $!\n"); 1 while <$pipe>; return $.; }

Replies are listed 'Best First'.
Re^4: system command
by megaurav2002 (Monk) on Oct 31, 2007 at 03:19 UTC
    OK Thanks.. But i ll be really surprised if there is no way i can use the output directed to STDOUT by system command within my program.
    Gaurav
    "Wisdom begins in wonder" - Socrates, philosopher

      huh? I've presented two ways of getting a child's output already! (qx// and open '-|')

      Update: Here's a third way:

      use IPC::Open2 qw( open2 ); sub line_count { my ($fname) = @_; my $pid = open2(my $fr_child, undef, 'cat', $fname) or die; 1 while <$fr_child>; waitpid $pid, 0; return $.; }
      You may not have noticed the
      qx//
      that ikegami's first response quoted.

      That command will capture the output of any system command run. See also the "backticks" operator, which is identical to qx.

           "As you get older three things happen. The first is your memory goes, and I can't remember the other two... " - Sir Norman Wisdom

      Why you think so?

      my $fileName = '/some/path/to/file.ext'; my $returnVal = `wc -l $fileName`;

        No, you've merely hidden the opening of the file down inside an external utility. The file is still being opened and completely read, you've just managed to introduce a layer of indirection and a fork/exec overhead.

        In order to count the number of lines in a file something is going to have to open the file and search through it for end-of-line markers. That is what he meant when said impossible.

        (Of course if you were dealing with a file that used fixed-length lines that still were newline terminated you could cheat and do it with stat and /, but for all normal intents and purposes "impossible" is still a reasonable pronouncement. :)