Pearl receiving / modifying a deep hash over an array list

I want to delete a hash element (of any depth) that has a first key like $key[0], a second key like $key[1]etc., until @keyit is completed.

For example, if @key=(23,56,78), then I want to manipulate $hash{23}{56}{78}.
I do not know in advance how many elements it @keyhas.

I am trying to use the following:

my %the_path;
my $temp=\%the_path;
for(my $cline=0;$cline<=$#keys;$cline++){
     my $cfolder=$keys[$cline];
     $temp->{$cfolder}={};
     $temp=$temp->{$cfolder};
}

But I'm not sure how to manipulate the element here. How to do it?

+3
source share
3 answers

Data :: Diver exists for exactly this purpose.

my $last_hash = Data::Diver::Dive( \%hash, @keys[0..$#keys-1] );
if ($last_hash) { delete $last_hash->{ $keys[-1] } }
+5
source

hashrefs , , ; hashref, .

my $hash_ptr = $my_hash_ref;
foreach my $key_num (0..$#keys) {
    my $key = $keys[$key_num];
    if (exists $hash_ptr->{$key}) {
        if ($key_num == $#keys) {
            delete $hash_ptr->{$key};
        } else {
            $hash_ptr = $hash_ptr->{$key}; # Go down 1 level
        }
    } else {
        last;
    }
}

: hashref , . , 1 node, - . , , .

+1

:

use strict;
use warnings;

my $hash = { foo => { here => 'there', bar => { baz => 100 } } };

## mutates input
sub delete_hash {
  my ( $hash, $keys ) = @_;
  my $key = shift @$keys;
  die "Stopped recursing $key doesn't exist"
    unless exists $hash->{$key}
  ;
  scalar @$keys
    ? delete_hash( $hash->{$key}, $keys )
    : delete $hash->{$key}
  ;
}

delete_hash( $hash, [qw/foo bar/] );

use XXX;
YYY $hash;

, . Perl- TCO :

if (scalar @$keys) {
  @_=($hash->{$key}, $keys);
  goto &delete_hash;
}
else {
  delete $hash->{$key}
}

, : [qw/foo bar baz/], bar -.

foo:
  bar: {}
  here: there
+1

Source: https://habr.com/ru/post/1761971/