Robert's Perl Tutorial

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


Writing your own grep and map functions

Finally, you can write your own functions:

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

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

@mapped  = map  { &isit } @stuff;
@grepped = grep { &isit } @stuff;

print join ":",@mapped,"\n";
print join ":",@grepped,"\n";

sub isit {
        ($word)=/(^.*)ing/;

        if (length $word == 3) {
                return "ok";
        } else {
                return 0;
        }
}

The subroutine isit first grabs everything up until 'ing', puts it into $word , then returns 'ok' if the there are three characters in $word . If not, it returns the false value 0. You can make these subroutines (think of them as functions) as complex as you like.

Sometimes it is very useful to have map return the actual value, rather than the result. The answer is easy, but not obvious. Remember that subroutines return the value of the last expression evaluated? So, in this case, do blocks. What if the expression was, very simply:

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

print join " ",map  { s/(^[gsp])/$1 x 2/e } @mapstuff;
print "\n";
print join " ",grep { s/(^[gsp])/$1 x 2/e } @grepstuff;

Now, make sure $_ is the last thing evaluated:

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

print join " ",map  { s/(^[gsp])/$1 x 2/e;$_} @mapstuff;
print "\n";
print join " ",grep { s/(^[gsp])/$1 x 2/e } @grepstuff;

and there you have it. Now you understand that you can go and impress your friends, but please don't count on success.