Jump to content

Apply a callback to an array: Difference between revisions

→‎{{header|Perl}}: Added spaces to blank lines to make code sample a contiguous block
(add Clojure)
(→‎{{header|Perl}}: Added spaces to blank lines to make code sample a contiguous block)
Line 570:
# create array
my @a = (1, 2, 3, 4, 5);
 
# create callback function
sub mycallback {
return 2 * shift;
}
 
# use array indexing
my $i;
Line 581:
print "mycallback($a[$i]) = ", mycallback($a[$i]), "\n";
}
 
# using foreach
foreach my $x (@a) {
print "mycallback($x) = ", mycallback($x), "\n";
}
 
# using map (useful for transforming an array)
my @b = map mycallback($_), @a; # @b is now (2, 4, 6, 8, 10)
 
# and the same using an anonymous function
my @c = map { $_ * 2 } @a; # @c is now (2, 4, 6, 8, 10)
 
# use a callback stored in a variable
my $func = \&mycallback;
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.