Let's pretend that you have a very good reason for wanting to create a hash of all of your CGI parameters. Perhaps such a reason might be that you want to assign defaults for fields that might come in empty.
As discussed above making all of these values global is bad (they'll pollute your namespace and mean that I can send in whatever variables I like and perhaps mess up your script) and using a hash in a regular expression as you had planned to is easy enough.
So you might do this this way:
use CGI;
use strict;
my $query = CGI->new();
# set up my defaults
my %parameters = (name => ["Anonymous"],
address => ["No fixed abode"],
phone => ["Not Available"]);
# pull everything out of param and put in
# my hash.
foreach my $key ($query->param())
{
$parameters{$key} = [$query->param($key)];
}
This will give you a hash of array references with all your values in them. We have to use array references because you might have a checkbox group or select list returning multiple values.
Note that if you're providing defaults, now is a good time to ensure you only get the parameters that you want, not all the ones that the user has given you. So change the foreach line to be:
foreach my $key (keys %defaults)
Now, you wanted to be able to substitute these values into an SQL statement. Let's pretend that you've already made them untainted. Please untaint them. This substitution can be done like this:
# then to do your substitution:
$SQLStatement =~ s/\$(\w+)/$parameters{$1}[0]/eg;
BUT be aware that this ONLY takes the first of all the multiple answers returned. This might come back and bite you some time. It would have happened even if you had turned all the parameters into globals though.
A solution, depending on your table design and lots of other things might be to do the following:
foreach my $key (keys %defaults)
{
foreach my $value (@$key)
{
$SQLStatement =~ s/\$(\w+)/$value/eg;
# then use your $SQLStatement ....
}
}
But that really does depend on what $SQLStatement looks like etcetera.
Hope this helps.
jarich
|