Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Columns to arrays

by Anonymous Monk
on Jul 01, 2004 at 23:29 UTC ( [id://371260]=perlquestion: print w/replies, xml ) Need Help??

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

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 <filename> | ./myprogram)

@LISTING=<STDIN>;

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.

Replies are listed 'Best First'.
Re: Columns to arrays
by jZed (Prior) on Jul 01, 2004 at 23:37 UTC
Re: Columns to arrays
by delirium (Chaplain) on Jul 01, 2004 at 23:44 UTC
    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
by beable (Friar) on Jul 01, 2004 at 23:47 UTC
    split() will do what you want, (see the documentation for split).
    #!/usr/bin/perl use strict; use warnings; my @arr0 = (); my @arr1 = (); while(my $line = <DATA>) { 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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://371260]
Approved by Old_Gray_Bear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2025-03-21 20:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When you first encountered Perl, which feature amazed you the most?










    Results (63 votes). Check out past polls.