• perl – 在脚本的不同部分使用不同的哈希值

    我有一个从文件中收集的哈希.下面的脚本将按预期打印所有值(注意我只包含脚本的重要部分,因此打开输入文件时不会添加太宽):

    use strict;
    use warnings;
    
    my %hash = ();
    while (<$fh>) {
      my ($region, $site, $layer) = split;
      push @{$hash{$region}}, "$region $site $layer";
    }
    foreach my $values(keys %hash) {
      print $values,"\n";
    }

    然而我的问题是我不想根据键打印所有值,我实际上想要通过告诉perl我想要的东西来分割值并在不同区域打印它们,而不仅仅是打印$values.

    例如,如果我有以下数据:

    North belair layer2
    North belair layer3
    East Monte layer2
    East Vista layer3

    我实际上希望能够在其他区域使用这些值,并打印如下内容:

    print "$site has layers: $layer"

    将打印:

    belair has layers: layer2 layer3

    Monte has layers: layer2

    Vista has layers: layer3

    要么

    print "$region has sites, $site and $site has layers: $layer";

    然后将打印:

    North has sites: belair and layers: layer2 layer3

    East has sites: Monte Vista and layers: layer2 layer3

    当我运行多个foreach循环时,我得到重复的结果,我不知道转到哪个方向.我所做的每一次搜索都只显示了如何打印键的所有$值

    my %sites;
    my %regions;
    while (<>) {
       my ($region_id, $site_id, $layer_id) = split;
    
       # Use hashes instead of arrays to remove duplicates.    
       ++$sites{$site_id}{layers}{$layer_id};
       ++$regions{$region_id}{layers}{$layer_id};
       ++$regions{$region_id}{sites}{$site_id};
    }
    
    # "Flatten" hashes into sorted arrays of unique elements.
    for my $site_id (keys(%sites)) {
       my $site = $sites{$site_id};
       $site->{layers} = [ sort keys(%{ $site->{layers} }) ];
    }
    
    for my $region_id (keys(%regions)) {
       my $region = $regions{$region_id};
       $region->{layers} = [ sort keys(%{ $region->{layers} }) ];
       $region->{sites}  = [ sort keys(%{ $region->{sites}  }) ];
    }
    
    # Now do what we want to do.
    for my $site_id (sort keys(%sites)) {
       my $site = $sites{$site_id};
       print "$site_id has layers @{ $site->{layers} }\n";
    }
    
    for my $region_id (sort keys(%regions)) {
       my $region = $regions{$region_id};
       print "$region_id has sites @{ $region->{sites} } and layers @{ $region->{layers} }\n";
    }
    相关文章
    相关标签/搜索
    香港最准一肖中特公开选料1 达州市| 桦南县| 桐乡市| 安图县| 剑川县| 裕民县| 池州市| 新营市| 久治县| 台湾省| 梁河县| 玉环县| 光山县| 漯河市| 泗阳县| 沛县| 汕尾市| 普洱| 安庆市| 南和县| 武城县| 岳阳县| 阿合奇县| 泰和县| 邹平县| 平遥县| 松原市| 静海县| 四子王旗| 馆陶县| 孟连| 甘德县| 敦煌市| 徐闻县| 元谋县| 油尖旺区| 富阳市| http://fa.hz0j2r0vo.fun http://fa.hz0j0r0vo.fun http://fa.hz0j1r1vo.fun http://fa.hz0j2r9vo.fun http://fa.hz0j0r2vo.fun