Perl:使用数组值创建散列

问题描述 投票:0回答:3

我对 perl 有点陌生,正在编写一个小脚本,它基本上以一种稍微非结构化的方式读取具有时间轴的文件,例如 -

Test/Month/January
Test/Month/February
Mock/Month/August
Practical/Month/June
Result/Month/October

基本上我想阅读它并构建一个散列,该散列将根据事件(测试/模拟/实际/结果)进行隔离,并且值将作为数组维护。所以对于上面的文件,当我运行我的脚本时,它应该输出以下哈希 -

{
    Timetable => { 'Test' => ['January', 'February'], 'Mock' => ['August'], 'Practical' => ['June'], 'Result' => ['October'] } 
}

时间表将是包含全部数据的外部哈希。建议和帮助表示赞赏。

perl
3个回答
0
投票

一个可能的解决方案是读取每一行并在

/
上拆分,检查返回的数组中是否有 3 个元素,然后检查中间元素是否等于
Month
。如果是这样,将最后一个元素推入一个数组,该数组通过散列变量中的第一个元素映射。

例子:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my %H; # first element is key - map to an array

while(<>) {
    chomp;
    @_ = split(m:/:,$_); # Test/Month/January

    # check that there are 3 elements and that the middle is `Month`
    # then push to the mapped array:
    push @{$H{$_[0]}}, $_[2] if(@_ == 3 && $_[1] eq 'Month');
}

print Dumper(\%H);

输出:

$VAR1 = {
          'Practical' => [
                           'June'
                         ],
          'Test' => [
                      'January',
                      'February'
                    ],
          'Result' => [
                        'October'
                      ],
          'Mock' => [
                      'August'
                    ]
        };

0
投票

您可以逐行读取输入,在

/Month/
上拆分每一行,然后将月份推送到存储在哈希事件键下的匿名数组中。

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

my $h;
while (<>) {
    chomp;
    my ($event, $month) = split m{/Month/};
    push @{ $h->{Timetable}{$event} }, $month;
}

0
投票

请参阅以下脚本,这会对您有所帮助。

#!/usr/bin/perl

use strict; use warnings;
use Data::Dumper;

my %hash;

while(<DATA>){
        chomp $_;
        my @data = split("/", $_);
        push (@{$hash{$data[0]}}, $data[2]);
}

print Dumper(\%hash);

__DATA__
Test/Month/January
Test/Month/February
Mock/Month/August
Practical/Month/June
Result/Month/October

结果:

$VAR1 = {
          'Practical' => [
                           'June'
                         ],
          'Result' => [
                        'October'
                      ],
          'Test' => [
                      'January',
                      'February'
                    ],
          'Mock' => [
                      'August'
                    ]
        };
© www.soinside.com 2019 - 2024. All rights reserved.