RE: New Quiz: "What does this code do?" (1-December-2006)
"Garrett, Philip \(MAN-Corporate\)" <[email protected]> Wed, 13 Dec 2006 17:05:09 -0500
| Newsgroups | gmane.comp.lang.perl.qotw.discuss |
|---|---|
| Message-ID | <[email protected]> |
Owen wrote: > On Fri, 1 Dec 2006 16:35:44 +0200 > Shlomi Fish <shlomif-ik1l9ssToec+JF/[email protected]> wrote: >=20 >> Hi all! >>=20 >> Well, it's been a while since we had a quiz so here's another what >> does this code do quiz:=20 >>=20 >> {{{{{{ >> my (@list) =3D >> ( >> grep { $cgi->param("$prefix$_") } >> map { /^${prefix}(\d+)$/ ? ($1) : () } >> $cgi->param() >> ); >> }}}}}} >>=20 >> $cgi is a CGI.pm instance. (in case you couldn't guess.) >>=20 >> A friend of mine whose perl is quite rusty had problems >> understanding this code.=20 >>=20 >> What does this code do? And can you guess in what context it was >> used?=20 >>=20 >> I'll reveal the solution after a 60 hours quota, and until then >> please send them to me in private. >=20 >=20 > I have waited 60 hours and more now. Just wondering if there was a > follow up to the message because like the friend above, I too have > problems understanding what was going on! =20 >1: my (@list) =3D >2: ( >3: grep { $cgi->param("$prefix$_") } >4: map { /^${prefix}(\d+)$/ ? ($1) : () } >5: $cgi->param() >6: ); Whenever I see construct like this that confuses me, I rewrite it so that the code actually goes in the same order as the operations, and turn all the temporary lists into named arrays. If the resulting code is clearer and does not negatively affect performance in a substantial way, I'll leave it. my $prefix =3D "form_field_"; # line 5 my @param_names =3D $cgi->param; # line 4 my @received_fields; for my $param_name (@param_names) { if ($param_name =3D~ /^${prefix}(\d+)$/) { my $field_number =3D $1; push @received_fields, $field_number; } } # line 3 my @list; for my $field_number (@received_fields) { if ($cgi->param("${prefix}${field_number}")) { push @list, $field_number; } } # @list now contains a list of numbers for which there are # populated form fields named "form_field_<number>". # ** it might contain duplicates, too # ** "populated" means non-empty and non-zero Another way, but it doesn't really clear things up much: my @params =3D $cgi->param; my @numbers =3D map { /^${prefix}(\d+)$/ ? ($1) : () } @params; my @list =3D grep { $cgi->param("$prefix$_") } @numbers; Regards, Philip