0

I have executed a unix command whose output has a number of columns separated by whitespaces.How to extract a column from it and put it into an array using Perl.

2
Contributors
1
Reply
2
Views
10 Years
Discussion Span
Last Post by kuom
0

Here's a quick script that will read the input from STDIN (<>) and chop everything by spaces, and construct a 2D matrix (2 dimensional array) out of it. Say, your input is something that looks like the output of the command [B]ps aux[/B] , then you can use this script to "echo" the input:

#!/usr/bin/perl
# save this file as script.pl
use strict;
my @array;
my $counter = 0;
while (<>) {
    chomp($_);
    my @line = split(/\s+/, $_);
    $array[$counter] = \@line;
    $counter++;
}
# Print out the 2D array
foreach my $line (@array) {
     foreach my $item (@$line) {
         print "$item\t";
     }
     print "\n";
 }

And you can pipe the input to it like this:

$ ps aux | ./script.pl

-Josh
www.qbangsolutions.com

josh dot kuo at qbangsolutions dot com

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.