Data::Rmap(3pm)
Data::Rmap(3pm) β from User Contributed Perl Documentation, bestie. We're folding that manual name in right here so you know what page you're on: Data::Rmap. It's the recursive-map, apply-a-block-to-a-data-structure situation, and it's lowkey iconic. π
πΈ NAME πΈ
Data::Rmap β recursive map, apply a block to a data structure β¨
π¦ SYNOPSIS π¦
Okay bestie, here's the vibe in code form:
$ 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' ]
π DESCRIPTION π
Bestie, here's the core: rmap BLOCK LIST β recursively evaluate a BLOCK over a list of data structures, locally setting $_ to each element, and return the list made of the results of those evaluations. $_ is your little handle to modify the elements. π₯
Data::Rmap currently traverses HASH, ARRAY, SCALAR and GLOB reference types and ignores others. Depending on which rmap_* wrapper you use, the BLOCK gets 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 means the BLOCK is called for the container reference before it's called for its elements (although see "recurse" below for post-order). The values of a hash are traversed in the usual values order, which may affect some applications.
If the cut subroutine is called in the BLOCK then the traversal stops for that branch. Say if you cut an array then the code is never called for its elements (or their sub-elements). To simultaneously return values and cut, simply pass the return list to cut: cut('add','to','returned');
The first parameter to the BLOCK is an object which maintains the state of the traversal. Methods available on this object are described in "State Object" below.
π EXPORTS π
By default you get:
rmap,rmap_all,cut
Optionally:
rmap_scalar rmap_hash rmap_array rmap_code rmap_ref rmap_to:types => [ qw(NONE VALUE HASH ARRAY SCALAR REF CODE ALL) ]:all => ... # everything
β¨ Functions β¨
The various names are just wrappers which select when to call the code BLOCK. 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.
rmap_to { ... } $want, @data_structures; β most general first.
Recurse the @data_structures and apply the BLOCK to elements selected by $want. The $want parameter is the bitwise "or" of whatever types you choose (imported with :types):
VALUEβ non-reference scalar, eg.1HASHβ hash referenceARRAYβ array referenceSCALARβ scalar reference, eg.\1REFβ higher-level reference, eg.\\1,\\{}NOT any reference type, seeScalar::Util'sreftype:perl -MScalar::Util=reftype -le 'print map reftype($_), \1, \\1'GLOBβ glob reference, eg.\*x(scalar, hash and array recursed, code too as of 0.63)ALLβ all of the above (notCODE)CODEβ code references (as of 0.63)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;
(ALL | CODE) and (ALL & !GLOB) might also be handy.
The remainder of the wrappers are given in terms of the $want for rmap_to.
rmap { ... } @list;β Recurse and call the BLOCK on non-reference scalar values.$want = VALUErmap_all BLOCK LISTβ Recurse and call the BLOCK on everything.$want = ALLrmap_scalar { ... } @listβ Recurse and call the BLOCK on non-collection scalars.$want = VALUE|SCALAR|REFrmap_hashβ Recurse and call the BLOCK on hash refs.$want = HASHrmap_arrayβ Recurse and call the BLOCK on array refs.$want = ARRAYrmap_codeβ Recurse and call the BLOCK on code refs.$want = CODErmap_refβ Recurse and call the BLOCK on all "normal" references:$want = HASH|ARRAY|SCALAR|REF. Note:rmap_refisn't the same asrmap_to {} REFcut(@list)β Don't traverse sub-elements and return the@listimmediately. For example, if$_is an ARRAY reference, then the array's elements are not traversed. If there's two paths to an element, both will need to be cut.
π State Object π
The first parameter to the BLOCK is an object which maintains most of the traversal state (except current node, which is $_). You will ignore it most of the time. The recurse method may be useful. Other methods should only be used in throw away tools, see TODO.
Methods:
recurseβ 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 "seen list" is used, the child nodes aren't reprocessed.codeβ The code reference of the BLOCK itself. Possible useful in some situations.seenβ Reference to the HASH 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.wantβ The$wantstate described inrmap_to.
π EXAMPLES π
# 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
# replace CODE with "<CODE>"
$ perl -MData::Rmap=:all -E 'say join ":", rmap_code { "<CODE>" } sub{},sub{}'
<CODE>:<CODE>
# look inside code refs with PadWalker
$ perl -MData::Rmap=:all -MSub::Identify=:all -MPadWalker=:all -MSub::Name
use 5.10.0;
my $s = sub {}; sub A::a { $s };
say join ", ",
rmap_code {
sub_fullname($_), # name string
map { $_[0]->recurse } closed_over($_) # then recurse the sub innards
} \*A::a, subname b => sub { $s };
# A::a, main::__ANON__, main::b
π Troubleshooting π
Bestie, beware comma after block:
rmap { print }, 1..3;
^-------- bad news, you get an 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 "Deep recursion" warnings if you test exists $_->{this}{that} instead of exists $_->{this} && exists $_->{this}{that} as you may follow a long chain of "this"s Alternatively use the no autovivification pragma to avoid this problem.
π¦ TODO π¦
- put for
@_in wrapper to allow parameters in a different wrapper, solve localizing problem. - 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.
rmap_args { } $data_structure, @argsform to pass parameters. Could potentially help localizing needs. (Maybe only recurse last item)- Benchmark. Use array based object and/or direct access internally.
- 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.
π SEE ALSO π
map, grep, Storable's dclone, Scalar::Util's reftype and blessed
Faint traces of treemap:
http://www.perlmonks.org/index.pl?node_id=60829
Update: various alternatives have appear over the years, Data::Visitor has a list.
π AUTHOR π
Brad Bowman <rmap@bereft.net>
π LICENCE AND COPYRIGHT π
okay bestie, legal era but make it cute πΈ
- Copyright (c) 2004- Brad Bowman (
rmap@bereft.net). All rights reserved. periodt.
This module is free software π«Ά you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic and perlgpl for the full receipts, iykyk πβ¨
β οΈ and now the dramatic part: this program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. no cap, that's the deal π no promises, just vibes and code.
and that's a wrap on Data::Rmap π
this page came to you from perl v5.36.0, dated 2022-11-29, and it's filed under Data::Rmap(3pm) β go forth and map those structures, bestie, you're gonna slay π¦π
π¦ where this page comes from
- debian bookworm: libdata-rmap-perl 0.65-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libdata-rmap-perl 0.65-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libdata-rmap-perl 0.65-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libdata-rmap-perl 0.65-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libdata-rmap-perl 0.65-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms