I'm trying to revisit a problem I've raised a few months ago.
It's pretty much OK for me to use workarounds, but we have junior
programmers who go crazy when I show them these workarounds. Not talking
about workarounds making the code unclear and cluttered.
The problem is with TT automatically deciding what's an array and what's a
scalar. CGI.pm returns a single array element when you have a single
checkbox in a group checked, and two array elements when there are two
boxes checked. TT will try to do the right thing and create a scalar in
the first case, but a list in the second. I've no way to force a list
context in TT for lvalue. The code will talk better than I. This code
tries to show that Perl does the right thing, whereas TT doesn't:
use CGI;
use Template;
my $cgi = CGI->new('foo=1&foo=2&bar=1');
# put everything in a scalar context
for ($cgi->param) {
print "$_ => ".$cgi->param($_)."\n";
}
# put everything in the list context
for ($cgi->param) {
my @values = $cgi->param($_);
print "$_ => ".join(",",@values)."\n";
}
print "---------------\n";
Template->new->process(\*DATA,{ cgi => $cgi});
__DATA__
[% # scalar context ? -- broken -%]
[% FOR p = cgi.param -%]
[% p %] => [% cgi.param(p) %]
[% END -%]
[% # list context ? -- broken -%]
[% FOR p = cgi.param -%]
[% vals = cgi.param(p) -%]
[% p %] => [% vals.join(",") %]
[% END -%]
[% # scalar/list context workaround? -- works but ugly -%]
[% FOR p = cgi.param -%]
[% vals = cgi.param(p) -%]
[% p %] => [% vals.size ? vals.join(",") : vals %]
[% END -%]
generates:
foo => 1
bar => 1
foo => 1,2
bar => 1
---------------
foo => ARRAY(0x82b1e8c)
bar => 1
foo => 1,2
bar =>
foo => 1,2
bar => 1
What we really need is to be have a syntax to force a list context. Doing
rvalue [] doesn't force it of course... Hmm, how about using @ :) so it'll
look like this:
[% FOR p = cgi.param -%]
[% @ vals = cgi.param(p) -%]
[% p %] => [% vals.join(",") %]
[% END -%]
This all reminds me of JavaScript (*shrug*) where you have exactly the
same problem when you can have a user select one checkbox or many.
Thanks!
_____________________________________________________________________
Stas Bekman JAm_pH -- Just Another mod_perl Hacker
http://stason.org/ mod_perl Guide http://perl.apache.org/guide
mailto:[EMAIL PROTECTED] http://apachetoday.com http://eXtropia.com/
http://singlesheaven.com http://perl.apache.org http://perlmonth.com/