http://www.perlmonks.org?node_id=1013643


in reply to Split a file based on column

Although your data's a good candidate for a CSV parsing module, perhaps the following will assist:

use strict; use warnings; while (<>) { if ( my ($col2) = /^\d+\|(\d+?)\|/ ) { open my $fh, '>>', 'sample_1_' . $col2 . '.txt' or die $!; print $fh $_; } }

Usage: perl scriptName.pl sample_1.txt

The regex captures the value in the second column, and that's used later in creating the file name. The file's opened for appending, and the line's written to it. Since a lexically-scoped file handle is used, the file's automatically closed at the end of the if code block.