Hi!
Verwendet ihr eigentlich use Switch oder programmiert ihr euren Switch selbst ?
Beispiel fuer use Switch: (Auszug aus Switch.pm)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/perl
use warnings;
use strict;
use Switch;
switch ($val) {
case 1 { print "number 1" }
case "a" { print "string a" }
case [1..10,42] { print "number in list" }
case (@array) { print "number in list" }
case /\w+/ { print "pattern" }
case qr/\w+/ { print "pattern" }
case (%hash) { print "entry in hash" }
case (\%hash) { print "entry in hash" }
case (\&sub) { print "arg to subroutine" }
else { print "previous case not true" }
} # switch
Beispiele fuer selbst programmierten Switch
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
62
63
64
65
66
67
68
69
70
#!/usr/bin/perl
use warnings;
use strict;
# Altvernative mit eval
# ~~~~~~~~~~~~~~~~~~~~~
my $key = 1;
my %switch = ( 1 => "f1('Hallo')",
2 => "f2",
3 => "f3",
);
print eval $switch{$key};
sub f1 {
shift, "\n";
}
sub f2 {
print "f2\n";
return;
}
sub f3 {
print "f3\n";
return;
}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# 1. Alternative ohne eval
# ~~~~~~~~~~~~~~~~~~~~~~~~
%switch = ( 1 => x1(1,3),
2 => x2(2,3),
3 => x3(3,3)
);
my $key1 = 1;
print $switch{$key1}."\n";
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# 2. Alternative ohne eval
# ~~~~~~~~~~~~~~~~~~~~~~~~
my $key2 = 2;
SWITCH:{
if ($key2 == 1) { print x1($key2,10), "\n"; last SWITCH;}
if ($key2 == 2) { print x2($key2,10), "\n"; last SWITCH;}
if ($key2 == 3) { print x3($key2,10), "\n"; last SWITCH;}
}
sub x1 {
$_[0] * $_[1];
}
sub x2 {
$_[0] * $_[1];
}
sub x3 {
$_[0] * $_[1];
}
Einfach mal aus Interesse gefragt!
Gruss\n\n
<!--EDIT|havi|1065083523-->