Thread Array of Hashes aus Datei anlegen (53 answers)
Opened by Flips87 at 2020-02-04 11:19

hlubenow
 2020-02-05 09:50
#191300 #191300
User since
2009-02-22
875 articles
BenutzerIn
[default_avatar]
Na gut, also ich w├╝rde das so machen:

Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/perl

use warnings;
use strict;

use Data::Dumper;

my $datei = 'test.txt';

sub prepareLine {
    my $line = shift;
    chomp($line);
    $line = lc($line);
    $line =~ s/\W+|\d|_/ /g;
    $line =~ s/^\s+|\s+$//; 
    return $line;
}

sub getCount {
    my $str = shift;
    my @arr = @_;
    my $count = 0;
    for my $i (@arr) {
        if ($i eq $str) {
            $count++;
        }
    }
    return $count;
}

my $fh;
open($fh, "<", $datei);
my @zeilen;
my $line;
my $i;
my $count;
while ($line = <$fh>) {
    $line = prepareLine($line);
    my @splitted = split(/ /, $line);
    my %hash;
    for $i (@splitted) {
        $count = getCount($i, @splitted);
        $hash{$i} = $count;
    }
    push(@zeilen, \%hash);
}
close($fh);

print Dumper(\@zeilen);

... wobei ich die RegEx in prepareLine() von Dir ungetestet ├╝bernommen hab'.
Last edited: 2020-02-05 09:52:43 +0100 (CET)

View full thread Array of Hashes aus Datei anlegen