chen li wrote:
Hi all,
Although I read the usage for grep and map using
perldoc -f grep or map I don't think I really get the
differences between them.
I have a small data set:
my @data=(
[1,2,3],
[4,5,6],
[7,8,9]
);
I want to reverse the elements in each row only but
not rows themselves I would expect the following
output:
my @reverse=(
[3,2,1],
[6,5,4],
[9,8,7]
);
Here is the script I write. What I find is that the
map function will give me the expected result but not
the grep function. Any comments?
Thanks,
Li
#!C:/Perl/bin/perl.exe
use warnings;
use strict;
use Data::Dump qw(dump);
my @data=(
[1,2,3],
[4,5,6],
[7,8,9]
);
my @reverse_map=map{[reverse @[EMAIL PROTECTED];
print "result of using map function\n",dump
@reverse_map;
my @reverse_grep=grep{[reverse @[EMAIL PROTECTED];
print "\n","result of using grep function\n",dump
@reverse_grep;
exit;
######output from screen#######
result of using map function
([3, 2, 1], [6, 5, 4], [9, 8, 7])
result of using grep function
([1, 2, 3], [4, 5, 6], [7, 8, 9])
map and grep are very different things. What you want here is map, and you've
used it exactly correctly, and you have a working program as evidence of this.
Both map and grep take a rule and a list to work with, and apply that rule to
each element of the list, but there the similarity ends.
Think of map as a kind of list-to-list transform - a 'mapping' in fact. The
result of map is the contents of the original list transformed by applying the
rule to each element in turn. To double every element of a list, for instance,
we could write
map $_ * 2, (1, 2, 3)
and map would return the list (2, 4, 6).
grep, on the other hand, is best thought of as a list filter. Its result is all
of the elements of the original list (unaltered) for which the rule evaluates to
a true value. As an example, the expression below takes the numbers 1 to 10 and
returns only the odd numbers in that list by using the remainder operator '%' to
test each each element in turn.
grep $_ % 2 == 1, (1 .. 10)
Here, grep returns the list (1, 3, 5, 7, 9)
In your own example, your call to grep used a rule which returned an anonymous
array reference every time. Since any reference is a true value, the call simply
passed through all of the elements of the original array.
I hope this helps you to understand better. As food for thought consider this: I
have said that map and grep are very different, but it is possible to implement
the functionality of grep fairly simply using map; can you think how? As a clue,
remember that map's rule - the first parameter - is evaluated in list context.
Cheers,
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>