简体   繁体   English

在perl中创建哈希哈希

[英]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 我想用xywl值创建一个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: 这仅返回文件名和$1的值,但我希望输出如下所示:

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

where am I doing wrong?! 我在哪里做错了?!

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! 如果您对它的工作方式有任何疑问,请告诉我!

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'
                         }
        };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM