gumby said:
Sandman <
[email protected]> wrote in message
Here is another of of attacking the problem. I realize this may get
out of hand if you have quite a few columns but its just a thought.
That's precisely why you should use split instead of RegExps in this
case. Someone wise once said "Use Regexps when you know what you want
to save, use split when you know what you want to throw away." You
don't (necessarily) know what you want to save - how many columns there
are. You do know what you want to throw away - all the space between
the fields, regardless of how many there are.
the test file contains the following data:
1 2 3
4.1 5 6
7 8 9
The Code:
unless(open FILE, test)
{
print "Failed to open the test file ($!).\n";
}
If the file fails to open, you print a message to STDOUT, and then keep
going with the program? This should be
open my $file, 'test' or die "Failed to open the test file ($!).";
while ( said:
{
my $line = $_;
$line =~ /([0-9.]+)\s+([0-9.]+)\s+([0-9]+)/;
why reassign $_ to $line if all you're doing is pattern matching it one
statement later?
print "$1 and $2 and $3\n";
Never, ever use $1, $2, $3 unless you know the pattern match succeeded.
You never check for that.
Another reason to not use regexps here: What if the numbers are in the
format such as -0.9? How about 5e4? Again, you know what you want to
throw away, you don't know what you want to keep.
}
close FILE;
The Output:
1 and 2 and 3
4.1 and 5 and 6
7 and 8 and 9
As you can see $(number) is the column you want as you rip through
the file. You can push the column onto an array using something like
push(@array, $3) and that would push the contents of each line in
column three onto @array. There is probably a \(letter) that will do
decimal numbers i know \d does digits.
No, there's not. There is a module on the CPAN that will allow you to
specify exactly what kinds of numbers you want, however.
Regexp::Common, I believe.
Anyway hope this helps
-gumby
Paul Lalli