Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations dencom on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I read in data by columns?

Status
Not open for further replies.

ITadvice

IS-IT--Management
Jul 22, 2008
38
US
I am trying to collect data from a text file that looks like this:

date/time name2 name3 name4 name5 name6 name7 name8
data data data data data data data data
data data data data data data data data

I want to put all of columns 1, 4 & 8 into an array. How do you read data into an array by columns instead of by rows?
 
If the data fields are fixed length, use the unpack() function. If they are not fixed length but have a well defined delimiter between fields, use the split() function. If they are not fixed length and do not have well defined delimiters you will have to resort to using more complex regular expressions to get the data out of the lines and into an array.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
The following reads all the data into a hash of arrays, one array per column, with the column headers as the hash keys.
Perl:
use strict;
use warnings;

my %data;
my @names;

while (<DATA>) {
   chomp;

   if ($. == 1) {
      @names = split;
      next;
   }

   my @cols = split;
  
   for (my $i = 0; $i < @cols; $i++) {
      push @{$data{$names[$i]}}, $cols[$i];
   }
}

print "$_: ", join(', ', @{$data{$_}}), "\n" foreach (sort keys %data);

__DATA__
date/time  name2  name3  name4  name5  name6  name7  name8
1 data   data   3 data   data   data   5
2 data   data   4 data   data   data   6
It assumes you have a rectangular matrix of data with no short rows...

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top