Leser: 2
6 Einträge, 1 Seite |
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
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];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
my %switch = (
1 => \&function1,
2 => \&function2,
4 => \&function3,
default => \&irgendwas,
);
my $key = 1;
if ($key and exists $switch{$key}) {
$switch{$key}->($params); # erst jetzt wird es ausgefuehrt
}
else { # default, wenn noetig
$switch{'default'}->($params);
}
6 Einträge, 1 Seite |