Recursive map, apply a block to a data structure
$ perl -MData::Rmap -e 'print rmap { $_ } 1, [2,3], \\4, "\n"' 1234 $ perl -MData::Rmap=:all rmap_all { print (ref($_) || "?") ,"\n" } \@array, \%hash, \*glob; # OUTPUT (Note: a GLOB always has a SCALAR, hence the last two items) # ARRAY # HASH # GLOB # SCALAR # ? # Upper-case your leaves in-place $array = [ "a", "b", "c" ]; $hash = { key => "a value" }; rmap { $_ = uc $_; } $array, $hash; use Data::Dumper; $Data::Dumper::Terse=1; $Data::Dumper::Indent=0; print Dumper($array), " ", Dumper($hash), "\n"; # OUTPUT # ['A','B','C'] {'key' => 'A VALUE'} # Simple array dumper. # Uses $self->recurse method to alter traversal order ($dump) = rmap_to { return "'$_'" unless ref($_); # scalars are quoted and returned my $self = shift; # use $self->recurse to grab results and wrap them return '[ ' . join(', ', $self->recurse() ) . ' ]'; } ARRAY|VALUE, [ 1, [ 2, [ [ 3 ], 4 ] ], 5 ]; print "$dump\n"; # OUTPUT # [ '1', [ '2', [ [ '3' ], '4' ] ], '5' ]
rmap BLOCK LIST
Recursively evaluate a \s-1BLOCK\s0 over a list of data structures (locally setting $_ to each element) and return the list composed of the results of such evaluations. $_ can be used to modify the elements.
Data::Rmap currently traverses \s-1HASH\s0, \s-1ARRAY\s0, \s-1SCALAR\s0 and \s-1GLOB\s0 reference types and ignores others. Depending on which rmap_* wrapper is used, the \s-1BLOCK\s0 is called for only scalar values, arrays, hashes, references, all elements or a customizable combination.
The list of data structures is traversed pre-order in a depth-first fashion. That is, the \s-1BLOCK\s0 is called for the container reference before is it called for it's elements (although see \*(L"recurse\*(R" below for post-order). The values of a hash are traversed in the usual \*(L"values\*(R" order which may affect some applications.
If the \*(L"cut\*(R" subroutine is called in the \s-1BLOCK\s0 then the traversal stops for that branch, say if you \*(L"cut\*(R" an array then the code is never called for it's elements (or their sub-elements). To simultaneously return values and cut, simply pass the return list to cut: \*(C`cut('add','to','returned');\*(C'
The first parameter to the \s-1BLOCK\s0 is an object which maintains the state of the traversal. Methods available on this object are described in \*(L"State Object\*(R" below.
By default:
rmap, rmap_all, cut
Optionally:
rmap_scalar rmap_hash rmap_array rmap_ref rmap_to :types => [ qw(NONE VALUE HASH ARRAY SCALAR REF OBJECT ALL) ], :all => ... # everything
The various names are just wrappers which select when to call the code \s-1BLOCK\s0. rmap_all always calls it, the others are more selective while rmap_to takes an extra parameter permitting you to provide selection criteria. Furthermore, you can always just rmap_all and skip nodes which are not of interest. Most general first. Recurse the @data_structures and apply the \s-1BLOCK\s0 to elements selected by $want. The $want parameter is the bitwise \*(L"or\*(R" of whatever types you choose (imported with :types): VALUE - non-reference scalar, eg. 1 HASH - hash reference ARRAY - array reference SCALAR - scalar refernce, eg. \1 REF - higher-level reference, eg. \\1, \\{} B<NOT> any reference type, see <Scalar::Util>'s reftype: perl -MScalar::Util=reftype -le 'print map reftype($_), \1, \\1' GLOB - glob reference, eg. \*x (scalar, hash and array recursed) ALL - all of the above NONE - none of the above So to call the block for arrays and scalar values do: use Data::Rmap ':all'; # or qw(:types rmap_to) rmap { ... } ARRAY|VALUE, @data_structures; (\s-1ALL\s0 & !GLOB) might also be handy. The remainder of the wrappers are given in terms of the $want for rmap_to. Recurse and call the \s-1BLOCK\s0 on non-reference scalar values. $want = \s-1VALUE\s0
Recurse and call the \s-1BLOCK\s0 on everything. $want = \s-1ALL\s0 Recurse and call the \s-1BLOCK\s0 on non-collection scalars. $want = VALUE|SCALAR|REF
Recurse and call the \s-1BLOCK\s0 on hash refs. $want = \s-1HASH\s0
Recurse and call the \s-1BLOCK\s0 on array refs. $want = \s-1ARRAY\s0
Recurse and call the \s-1BLOCK\s0 on all references (not \s-1GLOBS\s0). $want = HASH|ARRAY|SCALAR|REF Note: rmap_ref isn't the same as rmap_to {} \s-1REF\s0
Don't traverse sub-elements and return the @list immediately. For example, if $_ is an \s-1ARRAY\s0 reference, then the array's elements are not traversed. If there's two paths to an element, both will need to be cut.
The first parameter to the \s-1BLOCK\s0 is an object which maintains most of the traversal state (except current node, which is $_). You will ignore it most of the time. The \*(L"recurse\*(R" method may be useful. Other methods should only be used in throw away tools, see \s-1TODO\s0
Methods:
Process child nodes of $_ now and return the result. This makes it easier to perform post-order and in-order processing of a structure. Note that since the same \*(L"seen list\*(R" is used, the child nodes aren't reprocessed.
The code reference of the \s-1BLOCK\s0 itself. Possible useful in some situations.
(Warning: I'm undecided whether this method should be public) Reference to the \s-1HASH\s0 used to track where we have visited. You may want to modify it in some situations (though I haven't yet). Beware circular references. The (current) convention used for the key is in the source.
(Warning: I'm undecided whether this method should be public) The $want state described in rmap_to.
# command-line play $ perl -MData::Rmap -le 'print join ":", rmap { $_ } 1,2,[3..5],\\6' 1:2:3:4:5:6
# Linearly number questions on a set of pages my $qnum = 1; rmap_hash { $_->{qnum} = $qnum++ if($_->{qn}); } @pages;
# Grep recursively, finding ALL objects use Scalar::Util qw(blessed); my @objects = rmap_ref { blessed($_) ? $_ : (); } $data_structure;
# Grep recursively, finding public objects (note the cut) use Scalar::Util qw(blessed); my @objects = rmap_ref { blessed($_) ? cut($_) : (); } $data_structure;
# Return a modified structure # (result flattening means we must cheat by cloning then modifying) use Storable qw(dclone); use Lingua::EN::Numbers::Easy;
$words = [ 1, \2, { key => 3 } ]; $nums = dclone $words; rmap { $_ = $N{$_} || $_ } $nums;
# Make an assertion about a structure use Data::Dump; rmap_ref { blessed($_) && $_->isa('Question') && defined($_->name) or die "Question doesn't have a name:", dump($_); } @pages;
# Traverse a tree using localize state $tree = [ one => two => [ three_one => three_two => [ three_three_one => ], three_four => ], four => [ [ five_one_one => ], ], ];
@path = ('q'); rmap_to { if(ref $_) { local(@path) = (@path, 1); # ARRAY adds a new level to the path $_[0]->recurse(); # does stuff within local(@path)'s scope } else { print join('.', @path), " = $_ \n"; # show the scalar's path } $path[-1]++; # bump last element (even when it was an aref) } ARRAY|VALUE, $tree;
# OUTPUT # q.1 = one # q.2 = two # q.3.1 = three_one # q.3.2 = three_two # q.3.3.1 = three_three_one # q.3.4 = three_four # q.4 = four # q.5.1.1 = five_one_one
Beware comma after block:
rmap { print }, 1..3; ^-------- bad news, you get and empty list: rmap(sub { print $_; }), 1..3;
If you don't import a function, perl's confusion may produce:
$ perl -MData::Rmap -le 'rmap_scalar { print } 1' Can't call method "rmap_scalar" without a package or object reference...
$ perl -MData::Rmap -le 'rmap_scalar { $_++ } 1' Can't call method "rmap_scalar" without a package or object reference...
If there's two paths to an element, both will need to be cut.
If there's two paths to an element, one will be taken randomly when there is an intervening hash.
Autovivification can lead to \*(L"Deep recursion\*(R" warnings if you test \*(C`exists $_-\*(C'{this}{that}> instead of \*(C`exists $_-\*(C'{this} && exists $_->{this}{that}> as you may follow a long chain of \*(L"this\*(R"s
put for @_ iin wrapper to allow parameters in a different wrapper, solve localizing problem.
Note that the package/class name of the \*(L"State Object\*(R" is subject to change.
The want and seen accessors may change or become useful dynamic mutators.
Store custom localized data about the traversal. Seems too difficult and ugly when compare to doing it at the call site. Should support multiple reentrancy so avoid the symbol table.
\*(C`rmap_args { } $data_structure, @args\*(C' form to pass parameters. Could potentially help localizing needs. (Maybe only recurse last item)
Benchmark. Use array based object and/or direct access internally.
rmap_objects shortcut for Scalar::Utils::blessed (Let me know of other useful rmap_??? wrappers)
Think about permitting different callback for different types. The prototype syntax is a bit too flaky....
Ensure that no memory leaks are possible, leaking the closure.
Read http://www.cs.vu.nl/boilerplate/
map, grep, Storable's dclone, Scalar::Util's reftype and blessed
Faint traces of treemap:
http://www.perlmonks.org/index.pl?node_id=60829
Brad Bowman <[email protected]>
Copyright (c) 2004-2008 Brad Bowman (<[email protected]>). All rights reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic and perlgpl.
This program is distributed in the hope that it will be useful, but \s-1WITHOUT\s0 \s-1ANY\s0 \s-1WARRANTY\s0; without even the implied warranty of \s-1MERCHANTABILITY\s0 or \s-1FITNESS\s0 \s-1FOR\s0 A \s-1PARTICULAR\s0 \s-1PURPOSE\s0.