#!/usr/bin/perl use strict; use warnings; open(FH,"input.txt")or die "can not open input file\n"; while (my $line=) { my (undef, undef, undef, $four, undef) = split("\t",$line); if ($four=~m/S(\d+)GM/){ my $F = get_file_handle($1); print $F $line; } } #### my %FHList; # Holds file handles we've opened so far sub get_file_handle { my $key = shift; if (!exists $FHList{$key}) { open $FHList{$key}, '>', "output_$key.txt" or die $!; } return $FHList{$key}; }