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; }