Regular Expressions: Examples
Find the lines with "Romeo" or "Juliet"
  • Let's find all the lines that have "Romeo" or "Juliet" on them somewhere.
    (Text of Romeo & Juliet from Project Gutenberg at )
  • Special variable $. means "current line number"
#!perl -w

use strict;

my $file = "rj.txt";
open( IN, "<$file" ) or die "Can't open $file: $!";
while (my $line = <IN>) {
    print "$.: $line" if ( $line =~ /Romeo|Juliet/ );
16:   Romeo, son to Montague.
18:   Mercutio, kinsman to the Prince and friend to Romeo.
19:   Benvolio, nephew to Montague, and friend to Romeo
23:   Balthasar, servant to Romeo.
27:   Peter, servant to Juliet's nurse.
34:   Juliet, daughter to Capulet.
35:   Nurse to Juliet.
223:   M. Wife. O, where is Romeo? Saw you him to-day?
264:                        Enter Romeo.
276:   Ben. It was. What sadness lengthens Romeo's hours?
314:     This is not Romeo, he's some other where.
415:                    Enter Benvolio and Romeo.
426:   Ben. Why, Romeo, art thou mad?
494:     God forbid! Where's this girl? What, Juliet!
What Is Perl?
Perl Resources
Running a Perl Program
Perl Thinking
Data Types
Strings: Single Quoted
Strings: Double Quoted
Scalar operations
Scalar comparisons
Using Lists
Control Structures
Hash Manipulation
File Handling
Regex Matching
Regex Matching: Ex. 1
Regex Matching: Ex. 2
Regex Replacing
Anonymous subs
Modules: File::Find
Modules: Internet
Modules: Win32::*
Everything Else
  Next page >>>