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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|