#!/usr/bin/perl -w # # create and test a "map2" function that behaves similar to the # built-in "map" function, but takes two lists instead of just one as # input. # # abigail wrote one that is much snazzier, but i can't find her web # page right now. # # similar to how "sort" takes its arguments, the block here should use # $a and $b for the two elements. the block is called in list # context, just as in the "real" map. use strict; use vars qw($a $b); sub map2 (&\@\@) { my ($code_ref, $a_ref, $b_ref) = @_; my $max_index = (@$a_ref < @$b_ref) ? @$a_ref : @$b_ref; my @rv; local ($a, $b); for (my $i = 0; $i < $max_index; ++$i) { ($a, $b) = ($a_ref->[$i], $b_ref->[$i]); push @rv, &$code_ref; } return @rv; } my @a = (1, 2, 3); my @b = (4, 9, 1); my @sum = map2 { $a+$b } @a, @b; my @product = map2 { $a*$b } @a, @b; $" = ", "; print "a=(@a)\n", "b=(@b)\n", "sum=(@sum)\n", "product=(@product)\n"; exit;