Leser: 24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#!/usr/bin/perl -w use strict; use warnings; my %test = ( '15.01.2011' => defined, '17.01.2011' => defined, '13.02.2011' => defined, '16.03.2011' => defined, '20.12.2011' => defined, ); foreach my $m (1..12) { if (grep {$_ =~ /\.0?$m\./} keys %test) { print "Monat $m gefunden!\n"; } }
2011-02-26T13:42:58 lichtkindalso alle 12 monate als keys, deren value wieder ein hash : monatstag > data.
2011-02-26T14:30:26 lichtkindich denk ab mehr als 2 daten pro monat lohnt es sich.
2011-02-26T19:42:53 Linuxeredit: wie ich sehe, schrieb FIFO das bereits weiter unten...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#!/usr/bin/perl -w use strict; use warnings; use List::Util qw(first); my %test = ( '15.01.2011' => defined, '17.01.2011' => defined, '13.02.2011' => defined, '16.03.2011' => defined, '20.12.2011' => defined, ); foreach my $m (1..12) { if (first { /\.0?$m\./ } keys %test) { print "Monat $m gefunden!\n"; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
my %found; my %notfound; @notfound{1..12} = (); my $re = join "|", keys %notfound; for my $key (keys %test) { if ($key =~ m/\.0?($re)\./) { my $month = $1 + 0; $found{$month} ||= 1; delete $notfound{$month}; $re = join "|", keys %notfound; # wenn alle gefunden, braucht man gar nicht mehr suchen last unless keys %notfound; } } say for keys %found;
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 50 51 52 53 54 55 56
#!/usr/bin/perl -w use strict; use warnings; use List::Util qw(first); use Benchmark; my %test; for my $j (1970..2020) { for my $m (1..12) { for my $t (1..31) { my $d = sprintf '%02d.%02d.%d', $t, $m, $j; $test{$d}++; } } } my %found; my $m_grep = sub { foreach my $m (1..12) { if (grep { /\.0?$m\./ } keys %test) { $found{$m} ||= 1; } } }; my $m_first = sub { foreach my $m (1..12) { if (first { /\.0?$m\./ } keys %test) { $found{$m} ||= 1; } } }; my $m_pq = sub { my %notfound; @notfound{1..12} = (); my $re = join "|", keys %notfound; for my $key (keys %test) { if ($key =~ m/\.0?($re)\./) { my $month = $1 + 0; $found{$month} ||= 1; delete $notfound{$month}; $re = join "|", keys %notfound; # wenn alle gefunden, braucht man gar nicht mehr suchen last unless keys %notfound; } } }; timethese(100, { 'grep' => $m_grep, 'first' => $m_first, 'pq' => $m_pq });
1
2
3
4
Benchmark: timing 100 iterations of first, grep, pq...
first: 13 wallclock secs (13.55 usr + 0.00 sys = 13.55 CPU) @ 7.38/s (n=100)
grep: 59 wallclock secs (58.09 usr + 0.17 sys = 58.27 CPU) @ 1.72/s (n=100)
pq: 1 wallclock secs ( 0.86 usr + 0.00 sys = 0.86 CPU) @ 116.41/s (n=100)
2011-02-27T20:05:01 FIFODie Größe Deines Hashes kann ja nicht sehr bedeutend sein