=~ String searching in Perl

by Geethalakshmi 2010-09-17 13:53:23

=~ String searching in Perl


The '=~" syntax is used to find/match specific contents in a variable.

$x = "One two three"
if ($x =~ /two/) (is true)

Use the '^' to signify 'starting with'

if ($x =~ /^two/) (is false, starts with one)

Use a trailing 'i' command to ignore case

if ($x =~ /one/i) (Is true because case is ignored)

Use '\b' to check for word boundaries

if ($x =~ /thre/) (Is true because 'thre' of 'three' is found)
if ($x =~ /thre\b/) (Is false because there is no word 'thre')

Use '\W' to find the first non-word character.
Use '.*' to represent current find results to end of value
Use a starting 's' to represent substitute and a trailing 'newvalue/'
By combining these commands you can extract the first word in a variable.

$saveoriginal = $x;
$x =~ s/\W.*//;

value of $x is now 'One'.

Tagged in:

541
like
0
dislike
0
mail
flag

You must LOGIN to add comments