You don't want a smarter sub so much as the ability to pass behaviors into a sub. This is known as a subref or coderef and is the basis for functional programming.
The idea is that you have a set of structures, just like your nested if-statements. You want to have a set of behaviors in that nested-if and you don't want to have to hard-code it all over the place.
sub nested_ifs {
my ($i_max, $j_max, @behaviors) = @_;
foreach my $i ( 1 .. $i_max ) {
foreach my $j ( 1 .. $j_max ) {
foreach my $behavior ( @behaviors ) {
$behavior->( $i, $j );
}
# Or, more succinctly:
# $_->( $i, $j ) for @behaviors;
}
}
}
sub func1 { ... }
sub func2 { ... }
nested_ifs( 10, 20, \&func1, \&func2, sub { my ($i,$j) = @_; print "I:
+ $i\n\tJ: $j\n"; } );
My criteria for good software:
- Does it work?
- Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.