Robert's Perl Tutorial

http://www.sthomas.net/roberts-perl-tutorial.htm


Grep

If you want to search a list, and create another list of things you found, grep is one solution. This is an example, which also demonstrates join again :

@stuff=qw(flying gliding skiing dancing parties racing);	# quote-worded list

@new = grep /ing/, @stuff;	# Creates @new, which contains elements of @stuff 
				# matching with 'ing' in them.

print join ":",@stuff,"\n";	# first makes one string out of the elements of @stuff, joined
				# with ':' , then prints it, then prints \n

print join ":",@new,"\n";

Remember qw means 'quote words', so word boundaries are used as delimiters instead. The grep function must be fed a list on the right hand side. On the left side, you may assign the results to a list or a scalar variable. Assigning to a list gives you each actual element, and to a scalar gives you the number of matches found:

@stuff=qw(flying gliding skiing dancing parties racing);

$new = grep /ing/, @stuff;

print join ":",@stuff,"\n";

print "Found $new elements of \@stuff which matched\n";

If you decide to modify the elements on their way through grep , you actually modify the original list. Be careful out there.

@stuff=qw(flying gliding skiing dancing parties racing);

@new = grep s/ing//, @stuff;

print join ":",@stuff,"\n";
print join ":",@new,"\n";

To determine what actually matches you can either use an expression or a block. Up to now we've been using expressions, but when things become more complicated use a block:

@stuff=qw(flying gliding skiing dancing parties racing);

@new = grep { s/ing// if /^[gsp]/ } @stuff;

print join ":",@stuff,"\n";
print join ":",@new,"\n";

Try removing the braces and you'll get an error. Notice that the comma before the list has gone. It is now obvious where the expression ends, as it is inside a block delimited with { } . The regex says if the element begins with g, s or p, then remove ing. The result is only assigned to @new if the expression is completely true - 'parties' does begin with p, so that works, but s/ing// fails so the overall result is false, and the value is not assigned to @new .