develooper Front page | perl.perl5.porters | Postings from February 2009

Is it possible to define a 'map'-like function?

Thread Next
Ed Avis
February 17, 2009 06:00
Is it possible to define a 'map'-like function?
Message ID:
(This question is esoteric enough that I hope perl5-porters is an appropriate
forum - if not, let me know.)

perlsub(1) gives examples of using a '&' prototype to define a 'mygrep' function
which works the same way as builtin 'grep'.  But is it possible to write a
'mymap' that behaves the same way as 'map'?  It appears not:

use warnings;
use strict;
use 5.010;

sub mymap(&@) {
    my ($f, @in) = @_;
    my @out;
    foreach my $i (@in) {
        push @out, $f->($i);
    return @out;

foreach (qw(a b c)) {
    say map { $_ } qw(x y z);
    say mymap { $_ } qw(x y z);

I expected the two lines to print the same output, but the builtin map produces
'xyz' each time while mymap produces 'aaa', 'bbb', 'ccc'.

Am I doing something wrong in the definition of mymap, or is it not possible to
write (in pure Perl) a function equivalent to 'map'?

Ed Avis <>

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About