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

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

Thread Next
From:
Ed Avis
Date:
February 17, 2009 06:00
Subject:
Is it possible to define a 'map'-like function?
Message ID:
loom.20090217T135546-178@post.gmane.org
(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 <eda@waniasset.com>


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About