#!/usr/bin/perl -w use strict; use warnings; my %group; foreach my $line () { $line=~/(^\d{2})(\.*?)/g; my $account = $1; if($account=~/$group{$line}/g) { open my $fH, ">", "$account.txt" or die "Can't open or create '$account.txt'\n"; print $fH " $line \n"; close $fH; }else{ open my $fH, ">", "$account.txt" or die "Can't open or create '$account.txt'\n"; print $fH " $line \n"; close $fH } $group{$line}++; } __DATA__ 01 The quick red fox and dog as test. 02 Time flies like an arrow, fruit flies like a banana. 02 Time flies like an arrow, fruit flies like a banana. 03 Now is the time for all good men to come to the aid of their party. 01 The quick red fox jumped over the lazy brown dog. 01 The quick red fox jumped over the lazy brown dog. 02 Time flies like an arrow. 03 Now is the time for all good men to come to the aid of their party and not going. 03 Now is the time for all.