in reply to Assistance in abstracting a common routine
My suggestion is to stop using @_ directly so much, and assign inputs to scalars. That will simplify your job a lot.
Not only will it be easier to read, it'll be easier to get right. Note that this was actually non-trivial to convert because it's not easy to remember what all the parameters are in my head. Lucky it wasn't too long of a function where I had to scan back too far (say previous page or something).package MySample; sub build_dropdown { # build_dropdown( \$DataObject , 'key_function', 'text_functi +on', 'Select A Header', 'preselectedValue' ); my ($obj, $key_f, $text_f, $header, $preselected) = @_; my @xml; if ( $header ) { push @xml , qq{<option value="">$header</option>}; push @xml , qq{<option value="">==========</option>}; } foreach my $id ( $obj->$key_f() ) { my $sel = ( $id == $preselected ) ? ' selected' : ''; push @xml , ("<option value=\"$id\"${sel}>" . $obj->$text_f($i +d) . '</option>'); } return join "\n" , @xml; }
That said, a few other stylistic points. You're overkilling your whitespace. And you don't need that leading & on calling HtmlDropDowns::build_dropdown. Finally, your comment at the top of build_dropdown is incorrect. Your example at the bottom of your post is accurate - there is no \ involved in the object that you pass in.
And one more point for good measure. Because of the way this code works, you can actually pass in code refs. Including anonymous code refs. For example:
That should work just fine. The extra shift is the "object" (undef in this scenario) being passed in.print HtmlDropDowns::build_dropdown(undef, sub { 1 .. 10 }, sub { shift; 'Entry ' . shift; }, 'Pick a number from 1 to 10', 5, );
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Assistance in abstracting a common routine
by nmerriweather (Friar) on Jan 17, 2006 at 05:18 UTC |