Redei has asked for the wisdom of the Perl Monks concerning the following question:
I'm puzzling over the use of map with user-defined functions. Here's some sample code:
The output is: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";
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:==>A B C<== { uc($_) } ==>A B C<== { my_uc($_) } ==>A B C<== uc, ==> <== my_uc,
Surprisingly, my new function sometimes works, and sometimes not. Here's the output from that second code fragment: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";
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?==>A B C<== my_new_uc, ==> <== my_uc, ==> <== my_new_uc,
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Problems with map(function, array)
by tobyink (Canon) on Dec 10, 2012 at 22:41 UTC | |
by Redei (Initiate) on Dec 12, 2012 at 14:06 UTC | |
Re: Problems with map(function, array)
by LanX (Saint) on Dec 10, 2012 at 21:21 UTC | |
by Redei (Initiate) on Dec 10, 2012 at 21:30 UTC | |
by LanX (Saint) on Dec 10, 2012 at 21:38 UTC | |
by Redei (Initiate) on Dec 10, 2012 at 21:26 UTC | |
by eyepopslikeamosquito (Archbishop) on Dec 10, 2012 at 21:36 UTC | |
by Redei (Initiate) on Dec 12, 2012 at 13:58 UTC | |
by LanX (Saint) on Dec 10, 2012 at 21:30 UTC |
Back to
Seekers of Perl Wisdom