perl gurus: quick question

silverpig

Lifer
Jul 29, 2001
27,703
12
81
So I've got this astro assignment where I have to write a program to search for periodicities in a data set. I have a decent knowledge of c++ and java, but I want to do it in perl :)

I'm getting the syntax pretty well so far but I have a question concerning how to extract data from a file and put it into an array(s). The data file format is:

0.111111 0.222222
0.333333 0.444444

etc. Basically two columns of numbers seperated by 3 spaces.

number1 space space space number2 \n

Okay, so I can open the file

open(FD, "< test.dat") or die("Couldn't open test.dat\n") ;

and I can create assign and do basic operations on arrays so far.

Here's what I want to do: Create 2 arrays of equal length and assign data from one column to one and from the other column to the second. I found a great howto perl site but all it says is:

Now let's look at how Perl gets data in and out of files.

=======
@file_data = <FD> ;
=======

Perl reads the entire contents of the file into the @file_data array. Perl considers each line to be everything up to the next line separator. By default that's '\n', but you can change it if you need to by redefining Perl's special variable '$/'. One case where you'd do that is if you wanted Perl to read the entire file into a string rather than an array.

So if I understand this correctly, if I just did this, my first array element would be the entire first line "0.111111 0.222222"

So how do I set the proper arguments so that each number gets read into a spot in the array?

TIA
 

notfred

Lifer
Feb 12, 2001
38,241
4
0
my @col1;
my @col2;
open FD, "test.dat";
while ( my $line = <FD> ){
$line =~ /^(.*?)\s\s\s(.*?)$/;
push @col1, $1;
push @col2, $2;
}
close FD;
 

mattg1981

Senior member
Jun 19, 2003
957
0
76
Originally posted by: notfred
my @col1;
my @col2;
open FD, "test.dat";
while ( my $line = <FD> ){
$line =~ /^(.*?)\s\s\s(.*?)$/;
push @col1, $1;
push @col2, $2;
}
close FD;


we just finished perl up at school but we never learned 'my' ... what is that do?
 

Davegod75

Diamond Member
Jun 27, 2000
5,320
0
0
my is like essentially making a variable local. It's a good habit to use my for everything and also put "use strict" at the top of your code
 

Nothinman

Elite Member
Sep 14, 2001
30,672
0
0
we just finished perl up at school but we never learned 'my' ... what is that do?

I would go back and ask the teacher why he skipped over some very basic, and arguably important, parts of perl.