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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.