Small point, but worth knowing, you could replace
$fields = @record -1;
with $fields = $#record;
That said, it seems wasteful to break the whole line into its constituent fields, just so that you can access the first field, especially as you are going to re-join all the other bits back together in order to write them back out. You can avoid the problem you are having, and both simplify and speed up your code by only breaking the line into the two parts of interest something like this.
(I've assumed the omitted OUTFILE on the print statement was a transcription error.)
#!/usr/bin/perl while ($line = <>){ my($first, $rest) = $line =~ m[(^.*?)\|(.*$)]; if ( open(OUTFILE, ">>$first") ) { print OUTFILE $rest; } else { die("cannot open $first"); } }
One further possibility is that as coded, your script re-opens the output file for every line. Whilst I am not sure how costly (or not) re-opening a file that you haven't closed is, you might be better to avoid it it by building a hash to hold the file handles.
#! perl -slw use strict; my %fhs; while(<>) { my ($first, $rest) = m[(^.*?)\|(.*$)]; open $fhs{$first}, '>>', $first or die "Couldn't open $first:$!" unless $fhs{$first}; print { $fhs{$first} } $rest; }
The only slightly unusual thing with the above code is the need to wrap curlies {} around the filehandle to tell the compiler that you want to use the hash element referenced as a filehandle and aren't trying to print to STDOUT but forgot the comma.
In reply to Re: $" seems not to be working
by BrowserUk
in thread $" seems not to be working
by azool
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |