stefl has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monks, I am trying to use the value of a string in multiple subroutines. I kind of see this as two problems (or rather, things I don't yet understand):
1 - If I instantiate a variable outwith the subroutines and give it a value in one subroutine, I am unable to get that value in subsequent subroutines.
2 - If I use a random string and use it in each subroutine, it has a different value in each subroutine. Is there any way to keep it static?
Code is given below. I have a feeling it's something really simple...
Thanks very much for any help!
#!/usr/bin/perl use strict; use warnings; no warnings "uninitialized"; use CGI ":standard"; # I have also tried: # my @chars = ("A".."Z", "a".."z", "0".."9"); # my $randomString; # my $file; # with the starred section (lines 38-41) # but this does not work - the variables are empty in subsequent subro +utines. # I have tried using 'our' rather than 'my' but no effect. ################################################# # The below variables are the ones that I would like to use in multipl +e subroutines ($randomString and $file) ################################################# my @chars = ("A".."Z", "a".."z", "0".."9"); my $randomString; $randomString .= $chars[rand @chars] for 1..8; my $file = $randomString.".txt"; # 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_animal => \&select_animal ); my $action = param("action"); my $execute = $dispatch{$action} || $dispatch{default}; $execute->(); exit; sub select_language { #**********# # $randomString .= $chars[rand @chars] for 1..8; # $file = $randomString.".txt"; #**********# 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] }), p("The randomly generated string is: $randomString<br>The file +name is: $file"), submit({-value => "Continue"}), endform; } sub select_color { print header(), start_html(), h2("Part Two"), startform, p("The randomly generated string is: $randomString<br>The file +name is: $file"), hidden({ -name => "action", -value => "select_animal", -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_animal { print header(), start_html(), h2("Almost Done!"), startform(), p("The randomly generated string is: $randomString<br>The file +name is: $file"), hidden({-name => "language"}), hidden({-name => "colour"}), p("Thanks for your help!"), endform; }
|
---|