When nesting map{}s inside each other, the inner map{} can not have any idea of what the outer map{}'s value of $_ is, without using a temporary variable, which is terribly inelegant. So I wrote this, which I intend to offer as a sacrifice on the altar of CPAN. Any comments are welcome.
package NestedMap;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(nestedmap);
use strict;
use warnings;
# [POD snipped out]
sub nestedmap(&@) {
my $f = shift;
map {
local @NestedMap::stack = ($_, @NestedMap::stack);
$f->($_);
} @_
}
You might use it thus (from the perldoc):
# show all combinations of (A,B,C) (a,b,c) and (1,2,3)
print join("\n",
nestedmap {
nestedmap {
nestedmap {
join('',@NestedMap::stack[0..2])
} qw(A B C)
} qw(a b c)
} qw(1 2 3)
);
update: thanks to broquaint for pointing out that the example only works in 5.8.0. To get it to co-operate with 5.6.1, change
nestedmap { ... } list
to
nestedmap sub { ... }, list
In reply to Nested map
by DrHyde
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.