in reply to system command

qx//

Of course, you could just do it in Perl.

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

Replies are listed 'Best First'.
Re^2: system command
by megaurav2002 (Monk) on Oct 31, 2007 at 03:04 UTC
    Thanks. But actually I want to find the total number of lines without opening the file. Also, i am keen to learn how can we use the output of system command (that is directed to STDOUT) within our program.
    Gaurav
    "Wisdom begins in wonder" - Socrates, philosopher

      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 $.; }
        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
      I want to find the total number of lines without opening the file
      There's simply no way to do that.

      If you use wc -l, it opens the file, reads through the content (counting newlines), closes the file and returns a count. Whether you do the reading in Perl, or some external program does, it still must occur.

      Also, i am keen to learn how can we use the output of system command (that is directed to STDOUT) within our program
      Use backticks:

      my $file = '/path/to/file'; my $output = `/bin/wc -l '$file'`;

      Note $file is subject to shell-escaping rules.

      Alternatively, you can use the pipe form of open as ikegami has already observed.

      -David

        Note $file is subject to shell-escaping rules

        Easily handled:

        my $file = '/path/to/file'; my $output = `/bin/wc -l \Q$file\E`;