Perl Tutorials -Part 66- Replacing using patterns

Posted on June 6, 2010. Filed under: Perl Tutorials |


#perl examples of pattern search and replace
$_ = 'A space divides each word.';
#strip out all spaces ('s' means search and replace, 'g' modifier, global)
s/ //g;
print;
print "\n";

$_ = 'twelfth night, or what you will.';
#captitalize the first letter of each word.
#[A-Za-z] matches alphabatic charater.
#[^A-Za-z] matches non-alphabatic charater.
#'e' modifier means we evaluate the replacement string as perl code.
#ucfirst function use the matched string as its parameter.
s/[A-Za-z]*[^A-Za-z]/ucfirst($&)/ge;
print;

Output:
1
2
Aspacedivideseachword.
Twelfth Night, Or What You Will.
Advertisements

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: