Dynamically/recursively building hashes in Perl?

前端 未结 5 1131
北恋
北恋 2020-12-19 04:45

I\'m quite new to Perl and I\'m trying to build a hash recursively and getting nowhere. I tried searching for tutorials to dynamically build hashes, but all I could find wer

5条回答
  •  伪装坚强ぢ
    2020-12-19 05:20

    This is a bit far-fetched, but it works:

    sub insert {
      my ($ref, $head, @tail) = @_;
      if ( @tail ) { insert( \%{$ref->{$head}}, @tail ) }
      else         {            $ref->{$head} = ''      }
    }
    
    my %hash;
    chomp and insert \%hash, split( '/', $_ ) while <>;
    

    It relies on autovivification, which is admittedly a bit advanced for a beginner.

    What would probably make any answer to your question a bit twisted is that you ask for empty strings in the leaves, which is of a different "type" than the hashes of the nodes, and requires a different dereferencing operation.

提交回复
热议问题