Sorry, to leave no explanation but this is fully working with your original flow though I swapped your if/else tree for a dispatch hash of actions and subs. The form contents at the end are getting written to the download as well so you can verify what’s there.
This kind of thing is okay but I wouldn’t call it best practices. Form state is often better saved in sessions (too complicated to do securely for this example) and the best forms redirect on successful POSTs… but that’s a big kettle of fish. What you have below does what you were trying to do and you seem to be thinking about security already so please always do and get a review before you put anything on a production box. Almost all beginner CGI/webcode is insecure on some level and sometimes—depending on what it touches and what the server allows—dangerously so .
#!/usr/bin/env perl
use strict;
use warnings;
no warnings "uninitialized";
use CGI ":standard";
my $csv_file = "/tmp/test.csv";
# Initial variables
my @languages = ("English", "Francais");
my @colours = ("Red", "Orange", "Yellow", "Green", "Blue", "Indigo",
"Violet", "Black");
my %dispatch = ( default => \&select_language,
select_color => \&select_color,
select_download => \&select_download,
download => \&download );
my $action = param("action");
my $execute = $dispatch{$action} || $dispatch{default};
$execute->();
# print CGI::Dump(); # Uncomment for debugging help.
exit;
sub select_language {
print header(),
start_html(),
h2("Welcome to this basic form"),
startform(),
hidden({ -name => "action",
-value => "select_color",
-override => 1 }),
popup_menu({ -name => "language",
-values => \@languages,
-default => $languages[0] }),
submit({-value => "Continue"}),
endform;
}
sub select_color {
print header(),
start_html(),
h2("Part Two"),
startform,
hidden({ -name => "action",
-value => "select_download",
-override => 1 }),
hidden({ -name => "language" }),
"<p>Please choose your favourite colour: </p>",
radio_group({ -name => "colour",
-values => \@colours,
-default => $colours[0],
-linebreak => "true" }),
submit({-value => "Continue"}),
endform;
}
sub select_download {
print header(),
start_html(),
h2("Almost Done!"),
startform(),
hidden({-name => "action",
-value => "download",
-override => 1 }),
hidden({-name => "language"}),
hidden({-name => "colour"}),
"<p>Download the CSV file if you dare.</p>",
submit({-value => "Download"}),
endform;
}
sub download {
my $ok = open my $fh, "<", $csv_file;
unless ( $ok ) # Ad hoc error handling, don't do this for real.
{
print header("text/plain"), "SORRY! $csv_file: $!";
exit 1;
}
print header(-type => "application/x-download",
-attachment => "arbitrary-name.csv" );
for my $param ( param() )
{
print join(",", $param, param($param)), $/;
}
print while <$fh>;
}