perl

时间:2018-04-26 20:23:56

标签: perl

如何对哈希值进行排序并将其计入相关键。

例如: push @ {$ name_hash {$ st_name}},$ end_name;

 $VAR1 = 'firstname')';
    $VAR2 = [
      'lastname1',
      'lastname1',
      'lastname1',
      'lastname2',
      'lastname2',
      'lastname2',
      'lastname3',
      'lastname3',
       ] 

我需要像

这样的表格
    `firstname : lastname1 : 3`  

    `firstname : lastname2 : 3`

    `firstname : lastname3 : 2`

我尝试使用一些计数器,但它在启动时失败,我只有多次值或在最后一个值的末尾(在本例中为lastname3)。

foreach $n (sort keys %name_hash) {
    $ecounter =0; $temp2 = "NA"; $tcount =0; $p =0;
    foreach $lastn (sort values @{$name_hash{$n}}) {
        $ecounter ++ if ($lastn eq $temp2);
        $tcount++;
        if (($tcount) > ($ecounter+1) ){
        print " $n : $temp2 : $ecounter+1\n";
        $ecounter=0; $tcount=1;
        $p =1 ;
        }
        $temp2 = $lastn ;

       }

    print "$n : $temp2 : $ecounter+1\n" if (!$p);

    }

2 个答案:

答案 0 :(得分:5)

使用哈希计算重复的名称:

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

my %name_hash = (
    firstname => [qw[
        lastname1 lastname1 lastname1
        lastname2 lastname2 lastname2
        lastname3 lastname3 ]]);

for my $first_name (sort keys %name_hash) {
    my %count;
    ++$count{$_} for @{ $name_hash{$first_name} };
    print "$first_name : $_ : $count{$_}\n" for sort keys %count;
}

答案 1 :(得分:0)

# setup data for testing
sub _GetNamesHash {
    my $names_hash = {
        'James' => [qw(Smith Jones Smith Adams Baldwin Kirk Smith)],
        'John'  => [qw(Smith Adams Smith Adams Henry Hancock)],
    };
    return $names_hash;
}

# count the last names for each first name
sub _CountNames {
    # start with a hash of first_name => arrayref of last_name
    my $names_hash = _GetNamesHash();

    # put into a hash of first_name =>
    # arrayref of hashref of last_name => count
    my $name_counts = {};
    foreach my $first_name (keys %$names_hash) {
        $name_counts->{$first_name} = {}; # hash of last_name => count
        foreach my $last_name (@{ $names_hash->{$first_name} }) {
            $name_counts->{$first_name}->{$last_name}++; # count this last_name
        }
    }

    # show counts
    foreach my $first_name (sort keys %$name_counts) {
        my $last_name_counts = $name_counts->{$first_name};
        foreach my $last_name (sort keys %$last_name_counts) {
            my $count = $last_name_counts->{$last_name};
            printf("%s : %s : %d\n", $first_name, $last_name, $count);
        }
    }

    return;
}