Created
September 24, 2010 15:56
-
-
Save yoshiki/595591 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!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