Hello Monks,
I'm reading Higher Order Perl and one of the examples is an "imap" function which acts like map only it takes a block and an iterator.
sub imap {
my ($transform, $it) = @_;
return Iterator {
my $next = NEXTVAL($it);
return unless defined $next;
return $transform->($next);
}
}
That code may as well be in greek because it makes no sense to me. So I figured I'd try to write my own map function to see how it works.
#!/usr/bin/env perl
use 5.010;
use strict;
use warnings;
sub foo(&@) {
my $coderef = shift;
my @params = @_;
my @ret;
while(@params) {
push @ret, $coderef->($_);
}
return @ret;
}
my @a = ( "1", "2", "3", "4", );
my @b = foo { $_ ** 2 } @a;
But that produces the error "Use of uninitialized value $_ in exponentiation (**) at coderef.pl line 19."
I know when I pass parameters to a subroutine or closure they are passed in in @_, so I tried to shift the parameter off @_, but that produces the same error (based on my understanding of perl, this second attempt should work... "Should" is funny word).
my @b = foo { $_ = shift; $_ ** 2 } @a;
my @b = foo { my $var = shift; $var ** 2 } @a;
What gives? How does map/grep work it's magic? And why doesn't my attempt work? I realize that all of the useful map functions have probably already been written, so this is more of an exercise in understanding, how could I write my own map function?
Thanks Monks!
Edit: Seems my problem was with my use of while instead of for, I thought while set $_, but I guess not.
Here's the version that works:
#!/usr/bin/env perl
use 5.010;
use strict;
use warnings;
sub foo(&@) {
my $coderef = shift;
my @params = @_;
my @ret;
for(@params) {
push @ret, $coderef->();
}
return @ret;
}
my @a = ( "1", "2", "3", "4", );
my @b = foo { $_ ** 2 } @a;
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.