Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use 5.16.1;
- use Data::Dumper;
- use constant DFLT_STRUCT_KEY_SEP => '\.';
- sub is_plain_scalar { defined($_[0]) && !ref($_[0]) && length($_[0]) }
- my $get_struct_val_r;
- $get_struct_val_rx = {
- 'ARRAY' => sub {
- # print Dumper {'ARRAY'=>\@_};
- my $i = shift $_[1];
- length($i) && $i =~ /^-?\d+$/;
- $_[0] = $_[0][$i];
- $#{$_[1]} >= 0
- ? do {
- if (my $s = $get_struct_val_r->{ref $_[0]}) {
- &$s
- } else {
- undef
- }
- }
- : $_[0]
- },
- 'HASH' => sub {
- # print Dumper {'HASH'=>\@_};
- $_[0] = $_[0]{shift $_[1]};
- $#{$_[1]} >= 0
- ? do {
- if (my $s = $get_struct_val_r->{ref $_[0]}) {
- &$s
- } else {
- undef
- }
- }
- : $_[0]
- }
- };
- sub get_struct_val {
- (my $refType = ref(my $struct = shift)) or return;
- my $pth = $_[0];
- is_plain_scalar($pth) or return;
- my $rxSep = is_plain_scalar($_[1]) ? $_[1] : DFLT_STRUCT_KEY_SEP;
- ($get_struct_val_r->{$refType} // sub { return })->($struct, [split qr($rxSep), $pth]);
- }
- my $hr = {
- 'a' =>
- [
- {
- 'b' =>
- {
- 'c' => [qw/d e f/]
- }
- }
- ]
- };
- print Dumper [ get_struct_val($hr, 'a.0.b.c.2') ];
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement