Paladin is right - you need to set
$, , not
$" .
Now I'd like to suggest a few changes (improvements?) to your code. I mean, TIMTOWTDI - but this is how I might write it...
use IO::File;
use strict;
$, = "|";
my %fh; # key=filename; val=filehandle
while (<>) {
my @record = split /\|/;
my $word1 = shift @record;
$fh{$word1} ||= IO::File->new("> $word1")
or die "Error opening $word1 for writing: $!\n";
$fh{$word1}->print( @record );
}
What's different?
- use strict;
- declare all variables with my, to pass use strict;
- Setting $, outside the loop. (Might even want to local it.)
- Since you're using the first field for one purpose, and printing the remaining fields, shift it off the array. Then you can print the whole array (what's left).
- Only open each output file once, and cache the filehandle in an array. To do this, need to use IO::File handles.
- include $! in the open() error message.
- use $_ as the loop iterator / input line. That's what it's for, and makes the code less cluttered.
Now for one further optimization: split the line directly to the desired variables:
while (<>) {
my( $word1, @record ) = split /\|/;
And to get really too clever:
( $fh{$word1} ||= IO::File->new("> $word1")
or die "Error opening $word1 for writing: $!\n"
)->print( @record );
Not meant as a criticism on you code; just offered as a different perspective.
jdporter
The 6th Rule of Perl Club is -- There is no Rule #6.