my $filepath = 'foo.txt'; open my $FOOFILE, '>>', $filepath or die "Couldn't open $filepath: $!\n"; print $FOOFILE "First line of text.\n"; for (1 .. 5) { #do a bunch of stuff do_other_stuff ($FOOFILE); } print $FOOFILE "The end."; close $FOOFILE;