On Mon, 17 Sep 2001, Bradshaw, Brian wrote:

> I am trying to assign key/value pairs to a hash based on whether a variable
> from an HTML form has a value or not.
>
> I have the code:
> if ($vSalutation)
> {
>   %arr_criteria = ("salutation" => $vSalutation);
>   print "<TR>\n";
>   print "<TD><SPAN CLASS=\"menubold\">Salutation:</SPAN></TD>";
>   print "<TD> $vSalutation </TD>\n";
>   print "</TR>\n";
> }
> if ($vNameL)
> {
>   %arr_criteria = ("last_name" => $vNameL);
>   print "<TR>\n";
>   print "<TD><SPAN CLASS=\"menubold\">Last Name:</SPAN></TD>";
>   print "<TD> $vNameL </TD>\n";
>   print "</TR>\n";
> }
>
> The assignment to %arr_criteria is working. However I have not found the
> method that will let me add a key/value pair instead of overwriting the
> existing one. I always have only 1 hash key afte this code is executed. Can
> I assign pairs to a hash on the fly, or do I need to find a different way to
> do it?

The way you are doing it, you are redefining your hash each time, not
adding new key/value pairs.  I would create hash first (outside your if
statements), and then add elements as you need them:

my %arr_criteria = ();

...

$arr_criteria{'last_name'} = $vNameL;

Perl will automatically create the hash element for you.

In fact, as far as organization goes, I would add the elements to the hash
initially, with sensible default values (even empty strings) and then test
to see if the hash element exists.  Are you using CGI.pm?  You can grab
ALL of the values from a form by using the Vars() function, which will put
everything nice and neat into a hash for you.  Then you can do:

if($vars{vNameL}) {

    # do stuff
}

And not even worry about adding the elements yourself.

-- Brett
                                          http://www.chapelperilous.net/
------------------------------------------------------------------------
"Consider a spherical bear, in simple harmonic motion..."
                -- Professor in the UCB physics department


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to