Gossamer Forum
Home : General : Perl Programming :

@array problems

Quote Reply
@array problems
Old Fortran programmer trying to learn Perl. Having problems with arrays. File consists of 4 fields separated by the pipe (|). I am trying to pull out each field from the line, then print each field.

This code does not split the 4 fields. The delimiter ($delim) is still present after the split. What's worse, foreach is putting each character, not field, into each column.

help

Sample from data file:
00-11-15|W|02:04:44|vote.txt|
00-11-15|W|02:05:50|tabletut.txt|


Code snippet:

open (DUMPME, "< $_[0]");
print "<table>\n";
while ($line=<DUMPME>) {
chomp($line);
print "<tr>";
@aray = split /$delim/, $line;
foreach $item (@aray) {
print "<td>$item</td>\n";
}
print "</tr>\n";
}
close <DUMPME>;


Quote Reply
Re: @array problems In reply to
| is a meta charatcer in a regex, and therefore needs to be escape. Reworked this a little for you, this works in my test. Make sure you're checking the value of $_[0] before perfoming the open operation, especially if $_[0] is derived from user input.

Code:
my $delim = '\|';

open (DUMPME, $_[0]) or die "Can't open file $_[0]: $!";
print "<table>\n";
while (<DUMPME>) {
chomp;
split /$delim/;
print '<tr>';
print "<td>$_</td>\n" foreach @_;
print "</tr>\n";
}
close (DUMPME) or die "Can't close file $_[0]: $!";
--mark

Installation support is provided via ICQ at UIN# 53788453. I will only respond on that number.
Quote Reply
Re: @array problems In reply to
Mark,

Thanks so much for your prompt reply and correct diagnosis of the problem. Re-read the chapter on regex in the "Camel", then read it again. Amazing what you discover if you read the book and documentation. Sorry to have troubled with with so trivial an item.

Sorry I was so long in issuing the thanks. In a humble effort to explain away this tardy reply, I offer that I tried to post a timely reply months ago, but it was late at night, and my PC locked up. That's not a valid excuse IMHO. I should have responded sooner, but got wrapped up in writing code.

In summary, I feel like I have made the transition to a Perl programmer. Starting to dream Perl code. Now, to produce the tight code like you and Alex write.

Thanks again.

Randy