ITmajor has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to collect information from a tab separated text file and generate a graph based on criteria from user. I will only collect information from the 1st, 4th & 8th columns. The first row contains column headers. How do I parse the data from the text file into a 2 dimensional array? I want to use GD Graph to plot a scatter graph. The text file looks something like this:
name1  name2  name3  name4  name5  name6  name7 name8 name9
data1  data2  data3  data4  data5  data6  data7 data8 data9
data1  data2  data3  data4  data5  data6  data7 data8 data9


I want to create an array that will look like this:

data1 data4 data8
data1 data4 data8
This will allow me to plot (x,y) scatter graphs based on user's criteria. For example: (data1,data3) or (data1,data8)

Replies are listed 'Best First'.
Re: Two dimension array from text file
by thezip (Vicar) on Jul 11, 2008 at 16:44 UTC

    Try this to see if it's what you need:

    use strict; use warnings; use Data::Dumper; my @array = (); while (my $line = <$ifh>) { push(@array, [ (split(/\t/, $line))[0,3,7] ]); } print Dumper(\@array);

    Update: BTW, in your spec, you say the 1st, 4th, and 8th column, but in your output data you show the 1st, 3rd and 8th columns. Which is it?

    Update: I see that you have updated your root node to reflect the corrected indices. Generally, it is considered to be polite to indicate (via an Update: such as this) that you have changed the wording/context of your node. Otherwise, it makes the respondents look like *they* made the mistake.


    Your wish is my commandline.
Re: Two dimension array from text file
by MidLifeXis (Monsignor) on Jul 11, 2008 at 16:59 UTC
Re: Two dimension array from text file
by samtregar (Abbot) on Jul 11, 2008 at 16:44 UTC
    open my $fh, "<", "file_name_here.txt" or die $!; my @data; my $header = <$fh>; while(<$fh>) { chomp; my @row = split "\t"; push @data, [ @row[0, 3, 7] ]; } close($fh) or die $!;

    If your TSV is more like a CSV - if it has quoting for example - the you should use Text::CSV_XS instead of split. But if it's just raw data and raw tabs this should work fine.

    -sam

Re: Two dimension array from text file
by karavelov (Monk) on Jul 11, 2008 at 16:45 UTC
    it will be something like
    my @array; while (<>){ next if $.<2; #skip 1st line push @array, [(split / /, $_)[0,2,7]]; }
    code is untested