Thread Conditional RegExp (8 answers)
Opened by PHilbs at 2010-02-20 20:44

sid burn
 2010-02-20 23:31
#133396 #133396
User since
2006-03-29
1520 Artikel
BenutzerIn

user image
Ich würde es insgesamt so lösen.

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
59
60
61
#!/usr/bin/env perl
# Core Modules
use strict;
use warnings;
use 5.010;
use utf8;
use open ':encoding(UTF-8)';
use open ':std';
use Carp;
use Try::Tiny;
use Data::Dumper;

{
    my $name   = qr/(?<n> [^,]++ )/xms;
    my $weight = qr/(?<g> \d++   )/xms;
    my $sex    = qr/(?<s> m|w    )/xms;

    my %types = (
        hund  => qr/\A (?<t> hund )  : $name , $weight , $sex \z/xms,
        katze => qr/\A (?<t> katze ) : $name , $sex \z/xms,
    );
    
    sub get_data {
        my ( $string ) = @_;
       
        # read type
        my $type;
        if ( $string =~ m/\A ([^:]++) : /xms ) {
            $type = $1;
        }
        else {
            croak "String [$string] is probably invalid";
        }
        
        # get data from string
        if ( !exists $types{$type} ) {
            croak "Don't knew what to do with type [$type].";
        }
        
        # return data
        $string =~ $types{$type};
        return { %+ };
    }
}

my @animals = (
    "hund:bello,12,w",
    "katze:mini,m",
    "maus:Mickey,12,w",
    "muahahahaha",
);

for my $animal ( @animals ) {
    try {
        my $data = get_data($animal);
        print Dumper($data);
    }
    catch {
        warn $_;
    };
}


Ausgabe:
Code: (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
$VAR1 = {
'n' => 'bello',
'g' => '12',
's' => 'w',
't' => 'hund'
};
$VAR1 = {
'n' => 'mini',
's' => 'm',
't' => 'katze'
};
Don't knew what to do with type [maus]. at ./match.pl line 60
String [muahahahaha] is probably invalid at ./match.pl line 60


Mit der Lösung ist es auch leicht erweiterbar. Möchtest du z.B. den Maus Typ unterstützen kannst du einfach folgende Zeile im hash %types hinzufügen.

Code (perl): (dl )
maus  => qr/\A (?<t> maus )  : $name , $weight, $sex \z/xms,


Einzige Bedingung ist das der String immer mit einem Typ anfängt der bis zum ersten Doppelpunkt geht.
Nicht mehr aktiv. Bei Kontakt: ICQ: 404181669 E-Mail: perl@david-raab.de

View full thread Conditional RegExp