0: #!/usr/bin/perl -w
1: #
2: # treemap BLOCK HASHREF
3: # treemap BLOCK ARRAYREF
4: #
5: # Works like map, for arbitrary nested data structures. Data are
6: # are modified in-place (unlike map). Returns the original reference.
7: # Hash keys are not modified.
8: #
9: # UPDATE: now handles scalar references, and trimmed an unnecessary line
10: # as suggested by dkubb (thanks!)
11: #
12: # Handles cyclical references just fine, thank you.
13: #
14: sub treemap (&$) { &_treemap }
15: sub _treemap {
16: my ($code, $node, $refs) = @_;
17: if (not my $type = ref $node) {
18: local $_ = $node;
19: $node = &$code();
20: }
21: elsif (not exists $refs->{$node}) {
22: undef $refs->{$node}; # sneaky, eh?
23: if ($type eq 'HASH') {
24: $node->{$_} = _treemap($code, $node->{$_}, $refs) for keys %$node;
25: }
26: elsif ($type eq 'ARRAY') {
27: $_ = _treemap($code, $_, $refs) for @$node;
28: }
29: elsif ($type eq 'SCALAR') {
30: $node = \_treemap($code, $$node, $refs);
31: }
32: }
33: $node;
34: }
35:
36: ####################### EXAMPLE #############################
37:
38: $data = {
39: 'nums' => [
40: 'one',
41: 'two',
42: 'three',
43: 'four',
44: [
45: 'five',
46: 'six',
47: [
48: 'seven',
49: 'eight',
50: ]]],
51: 'two' => '2',
52: 'doh' => \'blah blah',
53: 'more' => {
54: 'a' => 'vala',
55: 'b' => 'valb',
56: 'c' => 'valc',
57: 'd' => 'vald'
58: }
59: };
60:
61: use Data::Dumper;
62: print Dumper treemap { "-=\U$_=-" } $data;
63: print Dumper treemap { s/\W/./g; $_ } $data;
64: print Dumper treemap { reverse lc } $data;
In reply to treemap
by MeowChow
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.