Re: [SPOILER] Re: New Quiz: "What does this code do?" (1-December-2006)

Joshua Kronengold <[email protected]> Thu, 14 Dec 2006 09:35:57 -0600
Newsgroups gmane.comp.lang.perl.qotw.discuss
Message-ID <[email protected]>
Shlomi Fish writes:
><<<<<<<<
>my(@list) =
>(
>    map { /^${prefix}(\d+)$/ && $cgi->param($_) ? $1 : () }
>        $cgi->param()
>);
>>>>>>>>>
>
>When I said that $1 may be destroyed by the param method call, he noted that 
>$1 was locally scoped, which indeed seems to be the case. So my code should 
>be written like that instead.

Wait, what?

This seems wrong -- since $1 is locally scoped, (not lexically
scoped), it -can- be technically destroyed by the param call, so you
don't want to do this, even if you can. (if param is written not to
squash $1, it's bad practice to trust in this).

However, it seems that at least in modern perls, $1 is -lexically-
scoped.  That seems new.  But good:

perl -Mstrict -e 'sub test { shift =~ /b(.*)/ and return $1 }; my 
$str = "abababa"; print +($str =~ /((?:ba){1,2})/ and print 
test($str),"\n") ? $1 : "no","\n"'
ababa
baba

(now, if while(<>) {} bashing $_ gets fixed, I'll be happy.
Surprised, but happy).

A checkbox group is how I'd certainly do it (and have done it), though
that doesn't help as much if you've got mixed values (a checkbox and a
textbox with a count, either of which, if changed, can select an
item.  Yeah, in the modern world, you can use javascript for this
nonsense, but then there are mobile browsers and paranoid people).

For short (if marginally less efficient) code, why not:

my @list = map +($cgi->param($_) ? /^$prefix(\d+)$/ : ()),$cgi->param;


-- 
       Joshua Kronengold (mneme@(io.com, labcats.org)) |\      _,,,--,,_  ,)
--^--   "Did you know, if you increment enough, you   /,`.-'`'   -,  ;-;;'
 /\\    get an extra digit?"  "I knew," weeps Six.    |,4-  ) )-,_ ) /\     
/-\\\   "We knew. But we had forgotten."	     '---''(_/--' (_/-'