in reply to Re: system command
in thread system command

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

Replies are listed 'Best First'.
Re^3: system command
by ikegami (Patriarch) on Oct 31, 2007 at 03:09 UTC

    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

        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`;
Re^3: system command
by erroneousBollock (Curate) on Oct 31, 2007 at 03:34 UTC
    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`;