use strict; use warnings; use CGI; my $cgi = CGI->new(); sub handle_error { print $cgi->header( -status => 500, -type => 'text/html', ); print ...; exit(0); } open(my $fh, '<', 'foo.csv') or handle error(...); print $cgi->header( # application/octet-stream might work better -type => 'text/csv', -attachment => 'foo.csv', ); print while <$fh>;