Skip to content

Instantly share code, notes, and snippets.

@exodist
Created October 8, 2015 23:41
Show Gist options
  • Save exodist/82db2a99d8c3f627ab1e to your computer and use it in GitHub Desktop.
Save exodist/82db2a99d8c3f627ab1e to your computer and use it in GitHub Desktop.
use strict;
use warnings;
use Test::More;
use Scalar::Util qw/reftype/;
sub redact {
my ($thing, $replace, @fix) = @_;
my %seen;
my @stack = ($thing);
while (@stack) {
my $it = shift @stack;
next unless ref $it;
next if $seen{$it}++;
if (reftype($it) eq 'ARRAY') {
push @stack => @$it;
next;
}
elsif (reftype($it) eq 'SCALAR') {
push @stack => $$it;
next;
}
elsif (reftype($it) ne 'HASH') {
next;
}
push @stack => values %$it;
for my $key (@fix) {
next unless defined $it->{$key};
$it->{$key} = $replace;
}
}
}
sub build {
my $orig = shift;
my $inner = {foo => $orig, bar => 'bar'};
my $scalar = \$inner;
my $it = {
foo => $orig,
bar => 'bar',
baz => [
{foo => $orig},
{bar => 'bar'},
],
uhg => $orig,
bam => $inner,
};
$it->{cycle} = $it;
};
my $foo = build('foo');
my $new = build('new');
redact($foo, 'new', qw/foo uhg/);
is_deeply(
$foo,
$new,
"Modified all necessary keys"
);
done_testing;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment