fs has asked for the wisdom of the Perl Monks concerning the following question:

I'm working on an existing CGI application. This app has defined a helper function for retrieving CGI parameters, which performs parameter specific validation. This function, named gParam, also uses wantarray(), and conditionally returns an array of values, or a scalar of the first requested value.

My problem occurs when this function is used to initialize hash values. For example:

my %hash = ( 'formval1' => gParam('formval1'), 'formval2' => gParam('formval2') );

If there is only one instance each of formval1 and formval2 passed, everything works fine. However, if more than one copy of, say, formval1 is passed in by a mischevious user or a bug on a preceding form, the returned array has multiple elements, and the contents of the hash are shifted and useless.

The problem seems to me to be with the usage of wantarray. Strictly speaking, it's correct in that the function is being called in a list context. Unfortunatelly, in the list context of hash initialization, I don't want it to ever return anything other than exactly one scalar value.

So the question, then, is there any way to tell in gParam when the caller is calling it from a hash initialization context? Or does anyone perhaps have some better, more generic way of handling this?

Replies are listed 'Best First'.
Re: Hash equivalent of wantarray?
by davorg (Chancellor) on Jan 19, 2006 at 14:06 UTC

    You probably want to enforce scalar context on the expression.

    my %hash = ( 'formval1' => scalar gParam('formval1'), 'formval2' => scalar gParam('formval2') );

    See also Want.pm.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Hash equivalent of wantarray?
by japhy (Canon) on Jan 19, 2006 at 14:05 UTC
    The situation you refer to has no context of its own -- it is merely list context. To that end, you must call gParam() in scalar context: formval1 => scalar(gParam("formval1")).

    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: Hash equivalent of wantarray?
by ysth (Canon) on Jan 19, 2006 at 21:31 UTC
    If all those needed scalar()s bother you, perhaps you should just:
    my %hash; $hash{$_} = gParam($_) for qw/formval1 formval2 .../;
    You even get rid of the repetition of each key name that way.