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.

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; }
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).

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:

print HtmlDropDowns::build_dropdown(undef, sub { 1 .. 10 }, sub { shift; 'Entry ' . shift; }, 'Pick a number from 1 to 10', 5, );
That should work just fine. The extra shift is the "object" (undef in this scenario) being passed in.

Replies are listed 'Best First'.
Re^2: Assistance in abstracting a common routine
by nmerriweather (Friar) on Jan 17, 2006 at 05:18 UTC
    first off -
    thanks a ton. it is quite easier to read. i'm the posterchild for premature optimization. i don't know why i do it. i just figured with something so short, it made sense to not bother using semantic scalars. i was clearly very wrong.

    anyways, the comment in the function was wrong, because that was from a different iteration - and i never updated things. the leading & is there purely as a visual cue - it just seems easlier looking at that as i scan the lines than looking all the way to the right to see if im calling 'new' in an oop instantiation.