|
08 Strings
$mystring
=
"Gary Beene"
$mystring
=
'Gary Beene'
$total
=
$mystring1
+
$mystring2
Single
or
double quotes are allowed
.
if
double quotes are used, variables placed inside the quotes are replaced with their value (interpolated)
.
if
single quotes are used, interpolation is
not
performed
.
Example:
$mystring1
=
"X"
$mystring2
=
"aaa$mystring1bbb"
In this example,
$mystring2
contains
"aaaXbbb"
Some important built
-
in Perl string functions include:
split
1.
@myarray
=
split
(
/
/
,
"The dog is mine"
)
# split string into array
# / / gives pattern for the split
2.
@myarray
=
split
(//,
"The dog is mine"
)
# // splits string into individual characters
3.
@myarray
=
split
(
"The dog is ming"
)
# if // is left out, whitespace is used
4.
@myarray
=
split
(/,/)
# if string is left out, split uses $_
5. (
$a
,
$b
,
$c
)
=
split
(/,/,
"One,Two,Three"
)
# string is split and assigned to variables
join
1.
@myarray
=
join
(
/
/
, (
$a
,
$b
,
$c
)
# split string into array
# / / gives pattern for the split
2.
@myarray
=
split
(//,
"The dog is mine"
)
# // splits string into individual characters
3.
@myarray
=
split
(
"The dog is ming"
)
# if // is left out, whitespace is used
4.
@myarray
=
split
(/,/)
# if string is left out, split uses $_
5. (
$a
,
$b
,
$c
)
=
split
(/,/,
"One,Two,Three"
)
# string is split and assigned to variables
reverse
1. string
$newstring
=
reverse
"1234"
# reverses the string
2. array
@newarray
=
reverse
@myarray
# reverses the elements
search
1.
index
index
string, substring, start_position
# return position of substring
# 0 is far left position
2.
rindex
index
string, substring, start_position
# from right, not left
3.
substr
string, offset,
length
# extract part of a string
# negative offset start from right
replace
substr
(
$a
,0,1)
=
"replacestring"
# replace 1st character with replacestring
substr
(
$a
,0,0)
=
"replacestring"
# put string at front of replacestring
substr
(
$a
,
-
7,7)
=
"replacestring"
# replace last 7 characters with replacestring
tr
/searchlist/replacementlist
# replace 1st list with 2nd list
tr
/ABC/XYZ/;
# replace A's with X's, B's with Y's, C's, with Z's
# work on $_
|