posted by 빠담아빠다 2016. 3. 10. 16:46

use Data::Dumper;

   my $foo = "a:b:c:d:a";

   my $bar = "a:b:c:d:z";

   my $hoh = {};

   sub createHash {

      my ($hoh,$str_orig,$str_rest,$lastkey,$parent) = @_;

      $str_rest = $str_rest || $str_orig || "";

      $_        = $str_rest;

      if (/^(.*?):(.*)$/)

      { 

         $parent    = $hoh;

         $hoh->{$1} = $hoh->{$1} || {};

         createHash($hoh->{$1},$str_orig,$2,$1,$parent);

      } 

      elsif (defined($lastkey)) 

      {

         delete($parent->{$lastkey}) if ref $parent->{$lastkey} ne "ARRAY";

         push (@{$parent->{$lastkey}} , [$str_rest,$str_orig]);

      }

      return $hoh;

   }

   $hoh = createHash($hoh,$foo);

   $hoh = createHash($hoh,$bar);

   print Dumper($hoh);