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

HI all. First time poster here, so please bear with me.

I have a real time data feed that I'm pulling data off of into a local port. The command I use to grab the data is "netcat localhost 12345".
This command works perfectly in the shell command line. The problem is that it runs continuously. To have it run only for 100 ms would be perfect.
In the Perl Script I am implementing this command with, my goal is to put each line into a string so I can parse the data, filter if need be, and do it again as a loop. The following commands are in a while(1) loop. I tried a number of things to get the data into a string line by line...

while(`netcat localhost 12345`) #because I know that backticked system commands return their output to the STDOUT

while(!`netcat localhost 12345`) #I thought maybe it worked with negative logic

$new_line = `netcat localhost 12345`; #This just didnt work at all...

`echo |netcat localhost 12345 >> $new_line`;

Unfortunately none have worked. I know that you can netcat the data into a file, but I would like to like to cut out the middle man, if possible. Hopefully someone knows a simple command that can help me.

  • Comment on Using Linux Commands in Perl - `Backticks`

Replies are listed 'Best First'.
Re: Using Linux Commands in Perl - `Backticks`
by Corion (Patriarch) on Sep 30, 2010 at 19:04 UTC

    See the pipe-form of open:

    my $cmd = 'netcat localhost 12345 |'; my $pid = open my $netcat, $cmd or die "Couldn't spawn [$cmd]: $!"; for (1..100) { my $line = <$netcat>; print $line; }; END { # Clean up leftover processes kill 9 => $pid if $pid; };
      The OP asked to have it run for 100ms, not 100 lines. Your program may hang for an unknown time, it may be days before you've read 100 lines.

      I would open a pipe, use a select loop and sysread to read from the pipe. After 100ms, terminate the loop and the pipe.

        Duh - I misread that. In that case, using select and alarm is likely the best approach.

        Luckily, the question is about Linux, where this approach will work. On Windows, reading from a pipe does not play well with select and/or IO::Select. The approaches of tunnelling the IO through (TCP) sockets (in the Win32 mkpipe emulation) do work for certain cases and horribly fail for other cases, always depending on the program spawned in such a fashion.

      Thank you so much... This works perfectly! I originally wanted to get one line, parse it, and move on to the next line, so I had thought that there was a netcat -option that would have it timed for you. This works much better, and I can get to the good stuff for the code now.

      Hopefully I can get some practice piping now, too. :)