Ulf
Ulf

Reputation: 83

How to read piped data in Perl?

I have a piece of python script, which I like to develop as a perl script. It use os.popen().readlines() to get information from the pipe. I don't understand how this works in Perl.

Can you help me, please?

Old Python Code:

hosts = os.popen('echo "GET hostgroups\nColumns: members\nFilter: name = HG_switches" | socat - /opt/colan/nagios/var/rw/live').readlines()
for item in hosts:
print item;

My Perl Code:

open (my $fh, "<", 'echo "GET hostgroups\nColumns: members\nFilter: name = HG_switches" | socat - /opt/colan/nagios/var/rw/live'while (<$fh>) {  or die $!;
while (<$fh>) { 
print $fh;
}

Upvotes: 0

Views: 99

Answers (1)

Sobrique
Sobrique

Reputation: 53488

Your mode to open isn't going to work. In order to open a pipe like that, you need to use a different symbol. < means 'open a file for reading', and you aren't.

You want;

open ( my $input_fh, '-|', $command_to_run ) or die $!;

But for something more extensive, you might want to look at IPC::Open2 and IPC::Run2 which allows you to open input and output filehandles.

open2 ( my $socat_stdou, my $socat_stdin, 'socat - /opt/colan/nagios/var/rw/live' );
print {$socat_stdin} "GET hostgroups\nColumns: members\nFilter: name = HG_switches";   
print <$socat_stdout>; 

IPC::Run3/IPC::Open3 give you STDERR as well. And you may find, you don't actually need to shell out to socat but can implement that natively.

Upvotes: 3

Related Questions