Basic HTML version of Foils prepared March 30 97

Foil 35 Regular Expressions -- Analogy with grep
(Chapter 7 of the Llama Book)

From PERL4 Tutorial for CPS616 Computational Science for Information Age Course CPS616 -- February 1995. by Geoffrey C. Fox


Regular expressions should be familiar as they are used in many UNIX commands with grep as best known
  • grep pattern file; # Prints out each line of file containing pattern
The rules for pattern are rich and we will discuss later -- consider here the simple pattern Fox
Then we can write the PERL version of grep as follows:
$line =0;
while (<>) {
  • if( /Fox/ ) { # Generalize to /Pattern/ to test positive if Pattern in $_
    • print $line, "$_"; } # $_ is current line by default
  • $line++; }
Another familiar operator should be s in sed (the batch or stream line editor) where
s/Pattern1/Pattern2/; # substitutes Pattern1 by Pattern2 in each line
The same command can be used in PERL with again substitution occuring on $_



© Northeast Parallel Architectures Center, Syracuse University, npac@npac.syr.edu

If you have any comments about this server, send e-mail to webmaster@npac.syr.edu.

Page produced by wwwfoil on Sat Sep 6 1997