--- "John W. Krahn" <[EMAIL PROTECTED]> wrote:

> chen li wrote:
> > 
> > --- Tom Phoenix <[EMAIL PROTECTED]> wrote:
> > 
> >>The expression in a map is evaluated in a list
> >>context. The list that
> >>it returns is included in the result list.
> >  
> >>The expression in a grep is a Boolean value, so
> it's
> >>evaluated in a
> >>scalar context. If it's true, the corresponding
> >>value from the list
> >>(that is, the value of $_ inside the expression)
> is
> >>included in the
> >>result list.
> >>
> >>These properties make grep useful for simply
> >>selecting elements from a
> >>list, while map is able to transform a list in a
> >>more general way.
> > 
> > So map function returns the transformed or changed
> > elements but not the original ones and grep still
> > returns the original ones? For example after
> certain
> > operation  A changes to B, in case of map the
> return
> > is B but in case grep the return  is still A. Is
> that
> > right?
> 
> Perl provides four basic list transformation
> functions:
> 
> NEW_LIST = grep    EXPRESSION, OLD_LIST;
> NEW_LIST = map     EXPRESSION, OLD_LIST;
> NEW_LIST = reverse             OLD_LIST;
> NEW_LIST = sort    SUB         OLD_LIST;
> 
> They all take an old list and potentialy modify it
> and return a different
> list.  The ONLY thing that they have in common is
> that (just like the
> for/foreach loops/statement modifiers) they alias $_
> so if $_ is modified the
> ORIGINAL DATA IS MODIFIED.
> 
> $ perl -le'
> my @a = qw/ 6 3 8 4 1 0 4 3 /;
> print "[EMAIL PROTECTED] = @a";
> my @b = sort @a;
> print "[EMAIL PROTECTED] = @a    [EMAIL PROTECTED] = @b";
> my @c = map { $_ *= 2 } sort @a;
> print "[EMAIL PROTECTED] = @a    [EMAIL PROTECTED] = @c";
> my @d = grep { $_ -= 1 } reverse @a;
> print "[EMAIL PROTECTED] = @a    [EMAIL PROTECTED] = @d";
> '
> @a = 6 3 8 4 1 0 4 3
> @a = 6 3 8 4 1 0 4 3    @b = 0 1 3 3 4 4 6 8
> @a = 12 6 16 8 2 0 8 6    @c = 0 2 6 6 8 8 12 16
> @a = 11 5 15 7 1 -1 7 5    @d = 5 7 -1 1 7 15 5 11
> 
> 
> Because of the way that grep evaluates its
> expression it cannot return
> anything that is not in the original list.  map
> however can return anything:
> 
> my @x = map { ( 'X' ) x 3 } 1 .. 3;
> 
> @x now contains ( 'X', 'X', 'X', 'X', 'X', 'X', 'X',
> 'X', 'X' ).
> 
> 
> map can imitate grep:
> 
> NEW_LIST = grep EXPRESSION,           OLD_LIST;
> NEW_LIST = map  EXPRESSION ? $_ : (), OLD_LIST;
> 
> But grep CANNOT imitate map.
> 
> 
> 
> 
> John


Thanks and they are really helpful.

Li

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to