-
Notifications
You must be signed in to change notification settings - Fork 33
/
named_parameters.pl
executable file
·80 lines (65 loc) · 1.66 KB
/
named_parameters.pl
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
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/perl
# Author: Daniel "Trizen" Șuteu
# License: GPLv3
# Date: 23 October 2015
# Website: https://github.com/trizen
# Code-concept for implementing the "named-parameters" feature in programming languages.
=for Sidef example:
func test (x, y, z) {
say (x, y, z); # prints: '123'
}
test(1,2,3);
test(1, y: 2, z: 3);
test(x: 1, y: 2, z: 3);
test(y: 2, z: 3, x: 1);
...
=cut
use 5.010;
use strict;
use warnings;
use List::Util qw(shuffle);
sub test {
my @args = @_;
my @vars = (\my $x, \my $y, \my $z);
my %table = (
x => 0,
y => 1,
z => 2,
);
my @left;
my %seen;
foreach my $arg (@args) {
if (ref($arg) eq 'ARRAY') {
if (exists $table{$arg->[0]}) {
${$vars[$table{$arg->[0]}]} = $arg->[1];
undef $seen{$vars[$table{$arg->[0]}]};
}
else {
die "No such named argument: <<$arg->[0]>>";
}
}
else {
push @left, $arg;
}
}
foreach my $var (@vars) {
next if exists $seen{$var};
if (@left) {
${$var} = shift @left;
}
}
say "$x $y $z";
($x == 1 and $y == 2 and $z == 3) or die "error!";
}
test(1, ['y', 2], 3);
test(1, 3, ['y', 2]);
test(1, ['z', 3], 2);
test(1, 2, ['z', 3]);
test(1, 3, ['y', 2]);
test(['y', 2], 1, 3);
test(['x', 1], ['z', 3], ['y', 2]);
test(shuffle(['x', 1], 3, ['y', 2]));
test(shuffle(['x', 1], 2, ['z', 3]));
test(shuffle(1, ['y', 2], ['z', 3]));
test(shuffle(['z', 3], ['x', 1], ['y', 2]));
test(shuffle(['z', 3], 1, ['y', 2]));