Using Regular Expression

$_ = "Hi Charles!";
if(m/Charles/) {
    print "/Charles/ matches!\n";
}

if(m(Charles)) {
    print "(Charles) matches!\n";
}

# try also m{Charles}, m[Charles] m<Charles>

if(m#Charles#) {
    print "#Charles# matches!\n";
}

# try also m!Charles! m^Charles^ m,Charles,
$_ = "http://www.math.ucla.edu";
if(m/^http:\/\//) {
    print "matches!\n";
}

if(m(http://)) {
    print "matches!\n";
}

Option Modifiers

File

abc
Abc
ABC
abC

Program

while(<>) {
    # abc ABC Abc etc
    if(/abc/i) {
        print $_;
    }  
}

What happens if "s" is removed?

$_ = "PIC20A : Java\nPIC40A : Perl\n";
if(/Java.*Perl/s) {
        print "Perl is after Java.";
}  

two modifiers can be put together

$_ = "PIC20A : Java\nPIC40A : Perl\n";
if(/java.*perl/si) {
        print "Perl is after Java.";
} 

The Binding Operator (=~)

print "Do you like Perl? ";
$likes_perl = (<STDIN>=~/\byes\b/i);
if($likes_perl) {
    print "You like Perl.\n";
}

Using Variable Interpolation in Patterns

$pattern = "hello";
chomp($_ = <STDIN>);
if(/$pattern/) {
    print "matched";
} else {
    print "not match";
}

Match Variables

$_ = "Hello there, neighbor";
if(/\s(\w+),/) { # memory word between space and comma
    print "the word was $1\n"; # the word was there
}
$_ = "Hello there, neighbor";
if(/(\S+) (\S+), (\S+)/) { # memory word between space and comma
    print "words were $1 $2 $3\n"; # words where Hello there neighbor
}

Substitutions

$_ = "PIC20A is a good.";
s/PIC20A/PIC40A/;
print; # PIC40A is good.
$_ = "My credit card number is 1234567812345678";
s/\d{16}/XXXXXXXXXXXXXXXX/;
"My credit card number is XXXXXXXXXXXXXXXX";
print; 
$_ = "He's out bowling with Amy tonight.";
s/with (\w+)/against $1/;
#He's out bowling against Amy tonight.
print;
$_ = "Amy is older than Ben!";
$temp = " is older than ";
s/(\w+)$temp(\w+)/$2$temp$1/;
# Ben is older than Amy!
print;
$_ = "Amy is very smart. Amy is studying in UCLA.";
s/Amy/Ben/;
# Ben is very smart. Amy is studying in UCLA.
print;
print "\n";
$_ = "Amy is very smart. Amy is studying in UCLA.";
s/Amy/Ben/g;
# Ben is very smart. Ben is studying in UCLA.
print;
print "\n";
$str = "Amy is very smart.";
$str =~ s/Amy/Ben/;
# Ben is very smart.
print $str;

split operator

$time="11:20:35";
@array = split /:/, $time;
# or @array = split(/:/, $time);
print "@array"; # 11 20 35

File

if($a == 5) {
  print "$a is equal to 5";
} else {
  print "Hello World\n";
}
while(<>) {
    chomp;
    @array = split(/[^a-zA-Z]+/, $_);
    print "@array\n";
}

if a
print a is equal to
else
print Hello World n