CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Map???

 



cir
Novice

Jan 28, 2001, 12:32 PM

Post #1 of 2 (421 views)
Map??? Can't Post

I've searched hard on the function map and can't find any good info about it. From what I gather map is like sort, except it sorts a string in the middle. Can anyone explain how to use it?

Thanks in advance.

http://cirw.cjb.net
http://cbible.cjb.net
http://gmail.cjb.net


rGeoffrey
User / Moderator

Jan 28, 2001, 2:05 PM

Post #2 of 2 (418 views)
Re: Map??? [In reply to] Can't Post

Simon Cozens wrote an article on map in October.

But the short answer is that it takes an array as input, does something to the elements, and spits out a new array. It is a good way to collapse some things where you would first think of using a foreach loop.

In this example you have an @oldarray and want to get a new one with all the elements in uppercase. You could do this...


Code
foreach (@oldarray) { 
$_ = uc ($_);
push (@newarray, $_);
}

But map will play with $_ for each element of the @oldarray just like the foreach loop...


Code
@newarray = map { uc($_) } @oldarray;

Because map and sort both take an array and give an array you will often see them together in a Schwartzian Transform that looks something like this...


Code
@newarray = map { ##recover code## } 
sort
map { ##build code## }
@oldarray;

A Schwartzian Transform is read from bottom to top.
The input is the @oldarray.
Then the first map takes the array and creates an array that is easier to sort.
Then sort does its thing.
Then the second map removes the real data from the extra stuff that was there for sort.
And lastly the real answer is spit out to the new array.

For an example of using it with sort do sort on the middle of something look at this thread from a few weeks ago... sort and print

Or read this paper A Fresh Look at Efficient Perl Sorting which won as best paper at The Perl Conference 3.0 (1999).





---
Sun Sep 9, 2001 - 1:46:40 GMT, a very special second in the epoch. How will you celebrate?

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives