Hi all!

The problem is this:

I don't fully understand how, when or why to use the map function - 

The first book I got on perl only mentions map in passing and says its syntax 
is the same as grep, but instead of returning $_, it returns the result of 
the map expression.

Now, if i try the code below:

        my @file = ("line 1", "line 2", "line 3", "line 4", "line 5");
        my @test = map {/5/} @file;

The result when I print @test is:
1

As I understand things, this is the m/5/ being "true" when it gets to the 
last element of the array ,"line 5" (- though if we had wanted the element of 
@file that matched we would have used grep).

So far so good -

A common example is:

        my @words = map {split ' ', $_} @file;

which splits the @file array into words using spaces.  Again, as I understand 
things, we get the words in @words because the split returns all the words 
from $_.

Would it be fair to say we would use map when we expect to have the 
expression return a list?

How would I go about creating a second array using map or grep without 
changing the original? Can I do that at all?

For example:

        my @elements = map {s/line/element/} @file;

just gives "11111" - the "true" values from the substitutions I assume, but 
changes @file. grep gives me the result in @elements that I want, but it, 
too, changes @file.

I know it sounds simple, but I just have the feeling that I'm missing some 
vital information, somehow :(

Thanks in advance for the help ;)

Tom Watson

Reply via email to