PYPL
PYPL

Reputation: 1849

creating hash of hashes in perl

I have an array with contain values like

my @tmp = ('db::createParamDef xy', 'data    $data1', 'model    $model1', 'db::createParamDef wl', 'data    $data2', 'model    $model2')

I want to create a hash of hashes with values of xy and wl

my %hash;
my @val;
for my $file(@files){
    for my $mod(@tmp){
        if($mod=~ /db::createParamDef\s(\w+)/){
        $hash{$file}="$1";
         }
         else{
            my $value = split(/^\w+\s+/, $mod);
        push (@val,$values);
         }
    $hash{$fname}{$1}="@val";
    @val=();
    }
}

this returns me only the filename and the value of $1, but i'm expecting output to be like this:

%hash=(
        'filename1'=>
                {
                'xy'=>'$data1,$model1',
                }
        'filename2'=>
                { 
                'wl'=>'$data2,$model2',
                }
    )

where am I doing wrong?!

Upvotes: 1

Views: 88

Answers (2)

mpapec
mpapec

Reputation: 50637

my @tmp = (
  'db::createParamDef xy', 'data    $data1', 'model    $model1', 
  'db::createParamDef wl', 'data    $data2', 'model    $model2'
);

my $count = 0;
my %hash = map {
  my %r;      
  if (my($m) = $tmp[$_] =~ /db::createParamDef\s(\w+)/) {

    my $i = $_;
    my @vals = map { $tmp[$i+$_] =~ /(\S+)$/ } 1..2;
    $r{"filename". ++$count}{$m} = join ",", @vals;          
  }
  %r;
} 0 .. $#tmp;

use Data::Dumper; print Dumper \%hash;

output

$VAR1 = {
          'filename1' => {
                           'xy' => '$data1,$model1'
                         },
          'filename2' => {
                           'wl' => '$data2,$model2'
                         }
        };

Upvotes: 1

hmatt1
hmatt1

Reputation: 5129

This was actually a pretty tricky problem. Try something like this:

#!/bin/perl
use strict;
use warnings;

my @tmp = ('db::createParamDef xy', 'data    $data1', 'model    $model1', 'db::createParamDef wl', 'data    $data2', 'model    $model2');
my @files = ('filename1', 'filename2');

my %hash;
my @val;
my $index = 0;
my $current;
for my $mod (@tmp) {
    if ( $mod=~ /db::createParamDef\s+(\w+)/){
        $current = $1;
        $hash{$files[$index]}={$current => ""};
        $index++;
        @val=();
    } else {
        my $value = (split(/\s+/, $mod))[1];
        push (@val,$value);
    }
    $hash{$files[$index - 1]}{$current} = join(",", @val);
}


use Data::Dumper;
print Dumper \%hash;

Let me know if you have any questions about how it works!

Upvotes: 1

Related Questions