<?xml version="1.0" encoding="windows-1252"?>
<node id="1015562" title="Re^3: Replacing values in an array" created="2013-01-27 00:37:15" updated="2013-01-27 00:37:15">
<type id="11">
note</type>
<author id="333489">
muba</author>
<data>
<field name="doctext">
&lt;p&gt;&lt;c&gt;map&lt;/c&gt; and &lt;c&gt;grep&lt;/c&gt; can be an intimidating functions, but quite useful once you understand them.&lt;/p&gt;

&lt;p&gt;Let's consider &lt;c&gt;grep&lt;/c&gt; first, since this one is a little simpler to grasp &amp;mdash; or at least, that was my experience. &lt;c&gt;grep&lt;/c&gt; takes two arguments, the second being a list of elements to work with, the first being the work that you want to have done on that list. You can specify that as a BLOCK, a code reference, or just the name of a function. &lt;c&gt;grep&lt;/c&gt; then loops over the list, aliasing &lt;c&gt;$_&lt;/c&gt; to each element in turn, and calls the given piece of code. Then it returns every element for which the code returned a true value.&lt;/p&gt;

&lt;c&gt;
my @numbers = (0, 0.5, 1, 1.5, 2, 2.5);

# Calling grep with a BLOCK:
my @integers = grep {int($_) == $_} @numbers;
print join(", ", @integers), " are integers.\n";

# Calling grep with a function name:
my @basket = ("apple", undef, undef, undef, "banana", "cherry", undef, "date");
print "The number of elements in \@basket is ", scalar(@basket), "\n";

my @basket_1 = grep defined, @basket;
print "The number of *defined* elements in \@basket is ", scalar(@basket_1), "\n";
&lt;/c&gt;

&lt;p&gt;See what happens? &lt;c&gt;grep&lt;/c&gt; returns the elements of the list you gave it, for which the piece of code returns true. The non-grep equivalents would be:&lt;/p&gt;

&lt;c&gt;
my @numbers = (0, 0.5, 1, 1.5, 2, 2.5);

# Calling grep with a BLOCK:
my @integers;
for (@numbers) {
    push @integers, $_ if int($_) == $_;
}
print join(", ", @integers), " are integers.\n";

# Calling grep with a function name:
my @basket = ("apple", undef, undef, undef, "banana", "cherry", undef, "date");
print "The number of elements in \@basket is ", scalar(@basket), "\n";

my @basket_1;
for (@basket) {
    push @basket_1, $_ if defined;
}
print "The number of *defined* elements in \@basket is ", scalar(@basket_1), "\n";
&lt;/c&gt;

&lt;p&gt;Now, &lt;c&gt;map&lt;/c&gt; is pretty similar, except that it allows you to change the elements:&lt;/p&gt;

&lt;c&gt;
my @numbers = 1..10;
my @times_ten = map { $_ * 10 } @numbers;
print join(", ", @times_ten), "\n";
&lt;/c&gt;

&lt;p&gt;Of course, these are just the basics &amp;mdash; the range of things you can do with them is astonishing. I hope this helps you along.&lt;/p&gt;</field>
<field name="root_node">
1015541</field>
<field name="parent_node">
1015550</field>
</data>
</node>
