How do I set global variables in a web service script so that they are
available to all functions? In my code below, and when called by the
client, the variable $str is empty within the helloWorld subroutine.
#!/bin/perl
use SOAP::Transport::HTTP;
SOAP::Transport::HTTP::CGI
->dispatch_to('DEMO')
->handle;
package DEMO;
my $str = "Hello World";
sub helloWorld {
my ($arg1, $arg2) = @_;
print "$str\n";
# do other stuff
}
For that case, use our() not my(), or predeclare the variable.
our() creates a package global.
This is not necessarily a true global, especially in a webserver
environment. That's probably what you want. I know you asked for a true
global, but I have some doubt as to whether you really want a true
global -- such would be shared with other requests and things and could
be bad: consider:
User 'schmoo' logs in and has the $handle variable set. You've made
this a true global.
Another user comes in and doesn't log in. The script is set to say
'Welcome, Guest' if the $handle variable isn't set or 'Welcome $handle'
if it is. You'd expect the second user to see 'Welcome Guest' but if
nothing specifically unsets $handle from being 'Schmoo' and $handle is
a true global, the unlogged in user will see 'Welcome Schmoo' instead.
This could be bad if, for instance, you have private information,
administrative functions, or consumer downloadables, for instance.
Secondly, such true globals will only be true to the server process
that they start in. Sone most webservers have anywhere form 5 to 500
child processes running to handle the traffic at one time, those would
be all entirely seperate processes.
So yeah, it's probably a package global you want, and therefore
our $variable = 'FooBar'