If you use the 3rd arg to split, you shouldn't need to worry about recombining the line. Also, your code doesn't print anything to OUTFILE, it always prints to STDOUT.
#!/usr/bin/perl while ($line = <>){ my ($file, $record) = split /\|/, $line, 2; if ( open(OUTFILE, ">>$file") ) { print OUTFILE $record; } else { die("cannot open $record[0]"); } }
Some stylistic tips: You can use the -n switch to perl to get an implicit while(<>){} loop around your code, and you can use the short-cut nature of or to simplify your conditional:
#!/usr/bin/perl -n my ($file, $rec) = split /\|/, $_, 2; # Good idea, jdporter and BrowserUk unless(exists $fh{$file}) { open $fh{$file}, ">> $file" or die "Can't open $file for append: $!\ +n"; } $fh{$file}->print $rec;
Or, as a one-liner:
perl -ne '($f,$r) = split /\|/, $_, 2; exists $fh{$f} or open $fh, ">> $f" or die "Can't open $f for append: $!\n"; print $fh{$f} $r;'
Update: I liked jdporter and BrowserUk's idea about caching the filehandles, so I added it. :)
bbfu
Black flowers blossom
Fearless on my breath
In reply to Re: $" seems not to be working
by bbfu
in thread $" seems not to be working
by azool
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |