Skip to content

Instantly share code, notes, and snippets.

@yoshiki
Created September 24, 2010 15:56
Show Gist options
  • Save yoshiki/595591 to your computer and use it in GitHub Desktop.
Save yoshiki/595591 to your computer and use it in GitHub Desktop.
#!perl
use strict;
use warnings;
use Data::Dumper;
my $ref = {
foo => {
qux => {
quux => 2,
},
bar => {
baz => 1,
},
},
};
_set_value( $ref, 'foo.qux.quux', 3 );
_set_value( $ref, 'foo.qux.quux.bar', 3 );
warn Dumper $ref;
sub _set_value {
my ( $a_ref, $key, $value ) = @_;
my $p = $a_ref;
for my $path ( split /\./, $key ) {
if ( ref $p->{ $path } && $key !~ /$path$/ ) {
$p = $p->{ $path };
}
else {
if ( $key =~ m/$path$/ ) {
$p->{ $path } = $value;
last;
}
else {
$p->{ $path } = {};
$p = $p->{ $path };
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment