Perl - find and save in an associative array word and word context

前端 未结 2 1234
眼角桃花
眼角桃花 2021-01-15 04:15

I have an array like this (it\'s just a little overview but it has 2000 and more lines like this):

@list = (
        \"affaire,chose,question\",
        \"ca         


        
2条回答
  •  日久生厌
    2021-01-15 04:40

    For each element in @list, split it at ,, and use each field as key of %te, push others to the value of that key:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Data::Dumper;
    
    my @list = (
        "affaire,chose,question",
        "cause,chose,matière",
    );
    
    my %te;
    
    foreach my $str (@list) {
        my @field = split /,/, $str;
        foreach my $key (@field) {
            my @other = grep { $_ ne $key } @field;
            push @{$te{$key}}, @other;
        }
    }
    
    print Dumper(\%te);
    

    Ouput:

    $ perl t.pl
    $VAR1 = {
              'question' => [
                              'affaire',
                              'chose'
                            ],
              'affaire' => [
                             'chose',
                             'question'
                           ],
              'matière' => [
                              'cause',
                              'chose'
                            ],
              'cause' => [
                           'chose',
                           'matière'
                         ],
              'chose' => [
                           'affaire',
                           'question',
                           'cause',
                           'matière'
                         ]
            };
    

提交回复
热议问题