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