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

my $value = $q->param('foo');
I would like the code above to return a scalar if the value of 'foo' is a scalar and an array ref if it is a multi-valued parameter. Is there a method for this within CGI or do I have to explicitly program the logic?

Replies are listed 'Best First'.
(ar0n) Re: CGI.pm: Can param return array ref?
by ar0n (Priest) on Jul 13, 2001 at 22:10 UTC
    my $value = @{ [ $q->param('foo') ] } > 1 ? [ $q->param('foo') ] : $q- +>param('foo');

    The above snippet creates an array ref and then derefences it, so it can check the number of elements. If it's greater than one, it creates array ref.

    ar0n ]

(tye)Re: CGI.pm: Can param return array ref?
by tye (Sage) on Jul 13, 2001 at 22:20 UTC

    my $value= [ $q->param('foo') ]; $value= $value->[0] if @$value < 2;
    also sets $value to undef if no such parameter exists (and, no, it won't generate a warning unless you later try to use $value in a string or number context).

            - tye (but my friends call me "Tye")
Re: CGI.pm: Can param return array ref?
by gremio (Acolyte) on Jul 13, 2001 at 22:12 UTC
    You have to explicitly program the logic, but it's not as simple as you'd like.

    CGI.pm explicitly returns you either a scalar, or if you ask for it and it's multivalued, then a list. It inherently can't know whether a parameter must be single valued, or just happens to be.

    What this means to you is that you should likely use
    @values = param('foo');
    
    and condition on list length of more than one. Better yet, keep track of which parameters *should* be multivalued, or use a naming convention like Hungarian.

    All the best,
    Gremio

    mail q.gremio..q.@..q.speakeasy..q@.@.q.org.;
Re: CGI.pm: Can param return array ref?
by DBX (Pilgrim) on Jul 13, 2001 at 22:29 UTC
    Thanks - all these responses were helpful and as ugly as the code I came up with 8-)