in reply to output file gives only last line

Move the file open and close outside the print loop. Note too that you should always check open results, use lexical file handles and use the three parameter version of open:

open my $out, '>', $fileName or die "Can't open '$fileName': $!\n"
Perl is the programming world's equivalent of English