-----Original Message-----
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] 
Sent: Tuesday, August 31, 2004 12:10 AM
To: [EMAIL PROTECTED]
Subject: Re: How do i run shell command


It works for me . Thanks

Sudhakar Gajjala





Chris Devers <[EMAIL PROTECTED]> on 08/30/2004 10:47:55 PM

Please respond to [EMAIL PROTECTED]

To:    Sudhakar Gajjala/C/[EMAIL PROTECTED]
cc:    [EMAIL PROTECTED]
Subject:    Re: How do i run shell command


On Mon, 30 Aug 2004 [EMAIL PROTECTED] wrote:

> I was trying to run System command from my perl Script . As i have
pipe
( |
> Anybody help me how to run shell command in Perl
>
> Here is the command :  system "cat $filename | wc -l";

You realize, of course, that this can be done entirely in Perl ?

Quoting from the excellent _Perl Cookbook_:

     [...] you can emulate wc by opening up and reading the file
yourself:

         open(FILE, "< $file") or die "can't open $file: $!";
         $count++ while <FILE>;
         # $count now holds the number of lines read

     Another way of writing this is:

         open(FILE, "< $file") or die "can't open $file: $!";
         for ($count=0; <FILE>; $count++) { }

     If you're not reading from any other files, you don't need the
$count
     variable in this case. The special variable $. holds the number of
     lines read since a filehandle was last explicitly closed:

         1 while <FILE>;
         $count = $.;

     This reads all the records in the file and discards them.

But if you really do need to do this via a system command -- you don't,
but I'll play along -- then the command as you've given it is what is
known as a Useless Use Of Cat.

This command --

     cat file | wc -l

-- is equivalent to this one --

     wc -l file

-- but the latter invokes less overhead, and so should be a bit faster.

Unless you really are conCATenating a chain of files together, most
commands of the form "cat foo | cmd" can be rewritten as "cmd foo" or,
maybe, "cmd < foo".



--
Chris Devers      [EMAIL PROTECTED]
http://devers.homeip.net:8080/blog/

np: 'It's Not Easy Being Green (lo-fi midi version)'
      by Kermit
      from 'The Muppet Movie Soundtrack'




Chris,

You are exactly right, that is a useless use of cat, old habits die
hard. And of course you are correct in that it can be done entirely in
perl, the availability of the shell cmd wc makes us lazy, and we don't
want to code what we can just call from the system.

Chris Hood




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to