R1-something.txt R2-something.txt DESCRP a DESCRP a 2 3 3 1 DESCRP b DESCRP c 3 5 4 9 #### a.txt b.txt c.txt R1a R1b R2c 2 3 5 3 4 9 R2a 3 1 #### foreach my $file (@{$fileArray}) { open (INPUT, "< $file") || die "Could not open $file\n"; while () { if ($_ =~ /^DESCRP/) { #get name of element chomp (my $newFileName = substr($_, 7)); #open/create file of that name open OUTPUT, ">> $newFileName.txt" || die "Could not open $_.txt\n"; #print the specific elements name print OUTPUT substr($file,0,2).$newFileName."txt\n"; } else { #or print the values following the element print OUTPUT $_; } } close OUTPUT; close INPUT; }