简体   繁体   English

Perl Loop添加到哈希

[英]Perl Loop add to Hash

I am trying to loop over all the values in my config file and put the data into an array. 我试图遍历我的配置文件中的所有值,并将数据放入数组中。 I just need to get the block as the key and then the setting name as the value. 我只需要将块作为键,然后将设置名称作为值即可。

#Config File looks like this

[Actions]
action=0
actionCR=1
actionHighlight=1

[Hotkeys]
key=38
keyCR=32
keyHighlight=39

[Settings]
chbAcronym=1
chbCompleted=0

# End Config




my %settingsTemplate;
my $settingsTemplate;

# Loop over each section in the template
foreach my $section (keys %{$cfg}) {

    # Loop over all the setting titles
    foreach my $parameter (keys %{$cfg->{$section}}) {

        # Push setting titles to an array
        $settingsTemplate->{$section} = $parameter;

    }
}

print Dumper($settingsTemplate);

$VAR1 = {
      'Hotkeys' => 'key',
      'Actions' => 'actionCR',
      'Settings' => 'chbAcronym'
    };

This is how it prints the array which isnt what i need. 这是它如何打印不需要的数组。

This is the desired output (not sure if my formatting is correct but hopefully you can understand it. 这是所需的输出(不确定我的格式是否正确,但希望您能理解。)

$VAR1 = {
      'Hotkeys',
             => 'key',
             => 'keyCR',
             => 'keyHighlight',
      'Actions',
             => 'action',
             => 'actionCR',
             => 'actionHighlight',
      'Settings',
             => 'chbAcronym',
             => 'chbCompleted'
    };

尝试这个:

push @{$settingsTemplate->{$section}}, $parameter;

As suggested, use a hash of arrays and push. 如建议的那样,使用数组的哈希并推入。

Note that you will not get the keys in the order they were in the file; 请注意,您将不会按密钥在文件中的顺序获得密钥。 I would recommend changing: 我建议更改:

foreach my $parameter (keys %{$cfg->{$section}}) {

to

foreach my $parameter (sort keys %{$cfg->{$section}}) {

so they have a consistent order, not one that varies. 因此它们具有一致的顺序,而不是变化的顺序。

Though the inner for loop is not actually needed; 尽管实际上不需要内部for循环; you can simply do: 您可以简单地执行以下操作:

# Loop over each section in the template
foreach my $section (keys %{$cfg}) {
    # Put setting titles into an array
    $settingsTemplate->{$section} = [ sort keys %{$cfg->{$section}} ];
}

or even more tersely: 或更简洁:

my $settingsTemplate = { map { $_, [ sort keys %{$cfg->{$_}} ] } keys %$cfg };

Your code performs an assignment instead of a push. 您的代码执行分配而不是推送。 Hashes in Perl only hold one value by default. 默认情况下,Perl中的哈希仅保留一个值。 You want a hash of arrays. 您想要一个数组的哈希。

http://perldoc.perl.org/perldsc.html#HASHES-OF-ARRAYS http://perldoc.perl.org/perldsc.html#HASHES-OF-ARRAYS

# Loop over each section in the template
foreach my $section (keys %{$cfg}) {

    # Loop over all the setting titles
    foreach my $parameter (keys %{$cfg->{$section}}) {

        # Push setting titles to an array
        push @{$settingsTemplate->{$section}}, $parameter;

    }
}

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

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