fork download
  1. #!/usr/bin/perl
  2. # your code goes here
  3. my $header = "F=8|A_C=3|A_B=2|D_G_H=11|D_B=2|E=5";
  4. use Data::Dumper;
  5. $Data::Dumper::Deparse = 1;
  6. print Dumper &unflatten($header);
  7.  
  8. sub unflatten {
  9. my ($data) = @_;
  10. my @fields = split /\|/, $data;
  11. my $result = {};
  12.  
  13. for my $datum (@fields) {
  14. my ($key, $value) = split /=/, $datum;
  15. my $key_is = &processline($key);
  16. print Dumper $key_is;
  17. #$result->{&processline($key)} = $value;
  18. }
  19. return $result;
  20. }
  21. sub processline {
  22. my ($key) = @_;
  23.  
  24. my ($first, $rest) = split /_/, $key, 2; # split key into at most 2 parts
  25. if($rest) {
  26. return { $first => &processline($rest) };
  27. # if the key is nested, there will be something in $rest
  28. # so recursively process the smaller $rest, and build up the result hashref
  29. }
  30. else {
  31. #print "first is $first\n";
  32. return $first;
  33. }
  34. }
Success #stdin #stdout 0.03s 5080KB
stdin
Standard input is empty
stdout
$VAR1 = 'F';
$VAR1 = {
          'A' => 'C'
        };
$VAR1 = {
          'A' => 'B'
        };
$VAR1 = {
          'D' => {
                   'G' => 'H'
                 }
        };
$VAR1 = {
          'D' => 'B'
        };
$VAR1 = 'E';
$VAR1 = {};