# This function works like map, except it produces a single scalar # output. It hence maps an array into a scalar hence the (clumsy) # name scalarmap # # It requires 3 parameters # 1) A code block like map. This will be passed $a and $b # $a will be the result and $b is the current element # it should return the new result # 2) An initial value # 3) An array sub scalarmap (&$@) { my $code = shift; local ($a, $b) = ( shift ); foreach $b (@_) { $a = &$code; } return $a; } # Here are some examples my @array = 1..10; my $sum = scalarmap { $a + $b } 0, @array; my $sum_of_even_numbers = scalarmap { $b & 1 ? $a : $a + $b } 0, @array; my $factorial = scalarmap { $a * $b } 1, @array; my $fancy_join = scalarmap { $a . $b } "", 'a'..'z'; # I don't suppose this will be actually useful in real life but it # amused me to make a twist an the all powerful map! # # This was inspired by a reference kudra made to subroutines and man # perlsub.