I'm assuming you can decipher how they work from the docs, and you're trying to figure out why you would use them.
There are many, many uses. Here are a few examples:
From the perldoc on readdir():
opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
@dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
closedir DIR;
Here grep was used to take the array from readdir() and filter out non-start-with-dot-files
Here's one I use often: I might have an array of values, that, at some point, I need to do a series of checks to see if a value is in the array.
It's inefficient to loop through the array multiple times. Likewise, we mostly need this data as an array, not a hash, this is just the exception. So we use map() to copy it to a hash:
my @array = qw(One Two Five Nine);
my %check_hash = map {$_ => 1} @array;
Now we can check for the existence of $foo in @array by checking $check_hash{$foo} for truth (or existence)
Let's say you're doing a database update, but you have a variable number of fields. In fact, you have the fields as @fields. Let's also assume you have a CGI object in $q that has all the needed fields there (and taint-checked)
@fields = qw(Name ID Age);
#assuming $dbh and $q exist, and primary key in $key
my $statement = 'update my_table '.join(",", map {"set $_ = ?"} @fie
+lds)." where Key=?";
my $sth = $dbh->prepare($statement);
$sth->execute(map({$q->param($_)} @fields), $key);
Unrolling this, we take each value in @field, and make it instead the text "set (value) =?". We then join those elements to end up with a legit SQL statement.
In the execute() call, we want the $q->param() value foreach element of field...so we use map() to get it.
What if we didn't have $key defined in the above? I mean, what if $key was the name of the field that was the primary key, and the value was taken from the passed parameters? A slight modification that would use grep():
@fields = qw(Name ID Age Key);
#assuming $dbh and $q exist, and primary key name in $key
#we don't want to change the value of the key!
my $statement = 'update my_table '.join(",", map {"set $_ = ?"} grep
+(!/^$key$/, @fields))." where $key=?";
my $sth = $dbh->prepare($statement);
$sth->execute(map({$q->param($_)} @fields));
Now the Key field is only used where needed. (Note this code woudl break if key wasn't last. It would be more durable if the execute() call also grepped out the key, then explicitly added it to the end:
$sth->execute(map({$q->param($_} grep(!/^$key$/, @fields)), $q->param(
+$key));
(And one last caveat -- $key will be interpretted as a regex. For alphanumeric keys, that's not a problem.)
Hope that helps, there are many more examples out there. In general, use grep when you need part of an array as an array, and use map when you need an array based off another list. If you need to actually execute code based on the contents of a list, you're better off using a loop.
|