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?