0: # This function works like map, except it produces a single scalar
1: # output. It hence maps an array into a scalar hence the (clumsy)
2: # name scalarmap
3: #
4: # It requires 3 parameters
5: # 1) A code block like map. This will be passed $a and $b
6: # $a will be the result and $b is the current element
7: # it should return the new result
8: # 2) An initial value
9: # 3) An array
10:
11: sub scalarmap (&$@)
12: {
13: my $code = shift;
14: local ($a, $b) = ( shift );
15: foreach $b (@_)
16: {
17: $a = &$code;
18: }
19: return $a;
20: }
21:
22: # Here are some examples
23:
24: my @array = 1..10;
25:
26: my $sum = scalarmap { $a + $b } 0, @array;
27:
28: my $sum_of_even_numbers = scalarmap { $b & 1 ? $a : $a + $b } 0, @array;
29:
30: my $factorial = scalarmap { $a * $b } 1, @array;
31:
32: my $fancy_join = scalarmap { $a . $b } "", 'a'..'z';
33:
34: # I don't suppose this will be actually useful in real life but it
35: # amused me to make a twist an the all powerful map!
36: #
37: # This was inspired by a reference kudra made to subroutines and man
38: # perlsub. In reply to scalarmap - some new perl syntax by ncw
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |