Columns to arrays
Anonymous Monk
created: 2004-07-01 19:29:29
Major newbie here, so please forgive my ignorance...

Here is what I am trying to do:
I have some data in a CSV file.

112233AABBCC,Homer Simpson
223344BBCCDD,Marge Simpson

There are about 3000 lines of it. I need to take this data and represent it like this:

Homer Simpson
112233AABBCC Some info

I want to take the file as input and output the data as a file. So basically, I got the data into an array like this: (I get the data in by using cat | ./myprogram)

@LISTING=;

Now what I want to do is get column 1 into an array and column 2 into a different array. I am assuming that Perl has some built in way to do this. I was looking at "split", but that is obviously not what I want.

Thank you for helping me.
Re: Columns to arrays
created: 2004-07-01 19:37:08
If all your data is like you showed (commas only as field separators, not embedded in fields; newlines as record separators, not embedded in fields), then split is what you want. If you have more complex data, then look at this: Comparison of the parsing features of CSV (and xSV) modules.
Re: Columns to arrays
created: 2004-07-01 19:44:17
Assuming the first column of data is never quoted, and there are always exactly two columns, split will work just fine. Otherwise, check out one of the CSV modules on CPAN.

Here is a solution using split:

for (@LISTING) {
  ($one,$two)=split /,/,$_,2;
  print "$two\n";
  print "$one some info\n";
}
Re: Columns to arrays
created: 2004-07-01 19:47:59
split() will do what you want, (see the documentation for [doc://split]).
#!/usr/bin/perl

use strict;
use warnings;

my @arr0 = ();
my @arr1 = ();

while(my $line = )
{
    chomp $line;

    # split on comma, to produce at most 2 fields
    # see perldoc -f split
    my @fields = split /,/, $line, 2;
    push @arr0, $fields[0];
    push @arr1, $fields[1];
}

print "arr0 = @arr0\narr1 = @arr1\n";

__DATA__
112233AABBCC,Homer Simpson
223344BBCCDD,Marge Simpson
323498XXYYZZ,Bart,has,commas,in,his,name,Simpson

perlmonks.org content © perlmonks.org and Anonymous Monk, beable, delirium, jZed

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03