Thread Gesetze vergleichen (3 answers)
Opened by andy at 2013-06-04 15:37

Linuxer
 2013-06-04 16:14
#167989 #167989
User since
2006-01-27
3875 Artikel
HausmeisterIn

user image
Wenn es relevant ist, kann man noch nachzählen lassen, welche Einträge nur in einer Datei vorhanden waren:

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
50
51
52
53
54
55
56
57
58
#! /usr/bin/perl
use strict;
use warnings;

use Data::Dumper;
$Data::Dumper::Sortkeys = 1;

my $in1 = 'data1.txt';
my $in2 = 'data2.txt';

my %hash1 = map { chomp; split m{;}, $_, 2 } grep { ! /^Kuerzel/ } do { open my $fh, '<', $in1; <$fh> };
my %hash2 = map { chomp; split m{;}, $_, 2 } grep { ! /^Kuerzel/ } do { open my $fh, '<', $in2; <$fh> };

my %result = ( %hash1, %hash2 );

# identify uniq entries
#  grep all keys from hash1 which are not in hash2, and vice versa
#  take the resulting lists of the two greps and use their values as hash keys for a new hash
my %single = map { $_ => 1 } ( grep { !exists $hash2{$_} } keys %hash1 ), ( grep { !exists $hash1{$_} } keys %hash2 );

# as alternative use two for-loops and iterate through keys of each hash and set each key individually
# for my $k ( keys %hash1 ) {
#    $single{$k}++       if not exists $hash2{$k};
#}
#for my $k ( keys %hash2 ) {
#    $single{$k}++       if not exists $hash1{$k};
#}

print Dumper( \%hash1, \%hash2, \%result, \%single );


__END__
* result (with comments):

# hash1 (from data1.txt)
$VAR1 = {
          'ABC' => 'abc',
          'DEF' => 'def',
          'GHI' => 'ghi'
        };
# hash2 (from data2.txt)
$VAR2 = {
          'ABC' => '123',
          'JKL' => 'jkl'
        };
# result (combination of hash1 and hash2)
$VAR3 = {
          'ABC' => '123',
          'DEF' => 'def',
          'GHI' => 'ghi',
          'JKL' => 'jkl'
        };
# single ( all uniq keys from both hashes)
$VAR4 = {
          'DEF' => 1,
          'GHI' => 1,
          'JKL' => 1
        };

Last edited: 2013-06-04 16:49:43 +0200 (CEST)
meine Beiträge: I.d.R. alle Angaben ohne Gewähr und auf Linux abgestimmt!
Die Sprache heisst Perl, nicht PERL. - Bitte Crossposts als solche kenntlich machen!

View full thread Gesetze vergleichen