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

I am new to perl and have been looking in tutorials and searching for an answer to no avail. I need to come up with a way to listen on a specific port for data coming in from a PBX and then append this data to a file. I was trying to use netcat for this but netcat will not stay open in the background.

I then tried to do something with perl but have hit a dead end. Here is what I am trying to run as a script

#!/usr/bin/perl use strict; use warnings; use IO::Socket; my $sock = new IO::Socket::INET ( LocalHost => '127.0.0.1', LocalPort => '6000', Proto => 'tcp', Listen => 1, ); die "Could not create socket: $!\n" unless $sock; my $new_sock = $sock->accept(); while(<$new_sock>) { print $_; } close ($sock);

this bit of code works and if I telnet to the box/port, I get everything I type on the screen. Now to take it a step further, I wanted to redirect this to a file and append it. I expect this to run in the background all day long as the PBX will be sending info on the calls that come in that we need for analysis.

I have tried redirecting the perl script at the command line

 perl receiver.pl >> /tmp/test_file

with no success and I have tried to add some logic in the script by adding a fh but that wasn't working either.

my $new_sock = $sock->accept(); while(<$new_sock>) { open my $fh, '>>', $file or die $!; close $fh;

Can anyone point me in the right direction here?

.Thanks, Steve

Replies are listed 'Best First'.
Re: script to listen on a port & redirect to a file
by ikegami (Patriarch) on Aug 14, 2015 at 18:43 UTC

    You forgot the print.

    Also, opening and closing the file for each line received is wasteful. Open the file before the loop.

      thanks for the quick reply.... so are you saying the script should look like this ?

      my $new_sock = $sock->accept(); open my $fh, '>>', $file or die $!; while(<$new_sock>) { print <$fh>; #######close $fh; }

      Is this what you mean?

      thanks, steve

        I think he means:

        [...] open my $fh, '>>', $file or die $!; while(<$new_sock>) { print $fh $_; } [...]

        Alternatively, just add:

        $|++

        before the "$sock->accept()" call in your original script and the redirect to file will work.