megaurav2002 has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,
I am writting a Perl Script in which i call system command to execute a command. for example :
my $returnVal = system("wc -l fileName");

Now i want to get the total number of lines in the file. But the $returnVal only stores the status of execution of system command i.e.success or failure. Any idea how can i get it to return me the number of lines in the file.
Thanks in advance
Gaurav
"Wisdom begins in wonder" - Socrates, philosopher

Replies are listed 'Best First'.
Re: system command
by ikegami (Patriarch) on Oct 31, 2007 at 02:56 UTC

    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 $.; }
      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 $.; }
        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

Re: system command
by downer (Monk) on Oct 31, 2007 at 03:43 UTC
Re: system command
by megaurav2002 (Monk) on Oct 31, 2007 at 04:32 UTC
    Thanks everyone for the help. I got a chance to learn couple of new things. BTW even after looking at the examples you guys provided i couldn't get it to run for so long because i didn't realise that i have to use ` instead i was using single code.
    Thanks again, Gaurav
    "Wisdom begins in wonder" - Socrates, philosopher
      There is more than one way ...
      :)
      open( FH, "file_name" ) or die $!; @lines = <FH>; $num_of_lines = @lines; print "NUm of lines : $num_of_lines\n";

      YOu may do it this way tooo...