DigiSlinger
DigiSlinger

Reputation: 29

Using Perl for taking command inputs

I'm having trouble with Perl reading in the output of a command.

The command in question: ps | grep |

I am trying to execute a script like this:

ps  | grep  | script.pl

where the output of "ps | grep | " will be used as input for the script to print out the status and its corresponding command.

Output:

0    command1
1    command2
....

I know in bash you can access an argument to be used as input by using "$#". Where # corresponds to its position in the command line. No clue in Perl.

Upvotes: 1

Views: 52

Answers (1)

ikegami
ikegami

Reputation: 385546

<> is short for <ARGV>. ARGV is a magical handle that reads from the files named by the elements of @ARGV, or from STDIN if @ARGV is empty (as is the case here). So all you need to do is read using <>.

For example,

#!/usr/bin/perl

use strict;
use warnings qw( all );

while (<>) {
   chomp;
   print "Got <$_>\n";
}

Output:

$ ps aux | grep pts | ./script.pl
Got <ikegami  22570  0.0  0.0 101028  3460 ?        S    Nov07   0:02 sshd: ikegami@pts/2 >
Got <ikegami  22571  0.0  0.0 129928  3456 pts/2    Ss   Nov07   0:00 -bash>
Got <ikegami  22865  0.0  0.0 127240  2432 pts/2    R+   18:12   0:00 ps aux>
Got <ikegami  22866  0.0  0.0 120540  2160 pts/2    S+   18:12   0:00 grep pts>
Got <ikegami  22867  0.0  0.0 129604  3928 pts/2    R+   18:12   0:00 /usr/bin/perl ./script.pl>

All that's left is to extract the information you want from the data you read in. Of course, you could simply use

ps ah -o tty,command

Upvotes: 4

Related Questions