I'm puzzling over the use of
map with user-defined functions. Here's some sample code:
sub my_uc {
my $c = shift;
return uc($c);
}
my @a = ('a'..'c');
@a = map { uc($_) } @a;
print "==>@a<== { uc(\$_) }\n";
@a = map { my_uc($_) } @a;
print "==>@a<== { my_uc(\$_) }\n";
@a = map uc, @a;
print "==>@a<== uc,\n";
@a = map my_uc, @a;
print "==>@a<== my_uc,\n";
The output is:
==>A B C<== { uc($_) }
==>A B C<== { my_uc($_) }
==>A B C<== uc,
==> <== my_uc,
Apparently Perl doesn't support the syntax
map function, array for user-defined functions. Or perhaps with this syntax it expects to find the function's argument in
$_. So here's my second try:
sub my_new_uc {
my $c = shift // $_;
return uc($c);
}
sub my_uc {
my $c = shift;
return uc($c);
}
my @a = ('a'..'c');
@a = map my_new_uc, @a;
print "==>@a<== my_new_uc,\n";
@a = map my_uc, @a;
print "==>@a<== my_uc,\n";
@a = map my_new_uc, @a;
print "==>@a<== my_new_uc,\n";
Surprisingly, my new function sometimes works, and sometimes not. Here's the output from that second code fragment:
==>A B C<== my_new_uc,
==> <== my_uc,
==> <== my_new_uc,
The information on
map in
perlfunc doesn't say anything about using your own functions except in the form
map { function($_) } @array and I couldn't find any help in other tutorials or FAQs. Does anyone know what is happening in my second example, and why
$_ sometimes is used in
map and sometimes not?
-
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.