#!/usr/bin/perl use strict; use warnings; # Ivan Novick # grep.pl # demonstrate the perl grep function to select members of an array my @fruits = ('apple', 'banana', 'cranberry', 'date', 'elderberry', 'fig', 'grape'); # grep for all fruits that end in the letter 'e' # return result as a new array my @some_fruits = grep { /e$/ } @fruits; # print out the fruits that were greped out of the original array for my $f (@some_fruits) { print "match: $f\n"; } print "=======================================================\n"; # create an array of numbers from 1 to 100 my @nums = (1 .. 100); # grep out all numbers that are divisible by 9 my @some_nums = grep { $_ % 9 == 0 } @nums; for my $n (@some_nums) { print "match: $n\n"; } print "=======================================================\n"; # a more complex multi-statement grep my @more_fruits = grep { my $fruit = $_; my $string_match = 0; my $length_match = 0; $string_match = 1 if ( $fruit =~ /a/ ); $length_match = 1 if ( length($fruit) > 5 ); # the result of grep is determined by the value of the last statement # in this case the last statement is a logical AND so both variables must evaluate to true # this implies that the fruit contains the letter 'a' and is greater than 5 characters in length $string_match && $length_match; } @fruits; for my $F (@more_fruits) { print "match: $F\n"; } print "=======================================================\n";