字符串的概念:
字符串就是一连串的字符。
字符串可以包含各种字符的任意组合。
最短的字符串是空字符串(即不含字符),最长的可填满所有可用的内存。
字符串的表示形式:
在Perl中, 字符串直接量有两种表示形式:单引号内的字符串与双引号内的字符串。
1:单引号内的字符串, 单引号内的所有字符都代表它本身(单引号和反斜线除外)。
要表示反斜线或单引号,需要在它之前加一个反斜线转义, 如:
'the dir is c://temp'
'/'//' #单引号后面接着反斜线
2:双引号的字符串, 它里面的反斜线可以有一个完整的概念:
如: “hello/tworld" #hello、tab、以及world
此外, 双引号内的的字符串还具有变量替换的功能,
如:
my $name = "peter";
...
my $mystr = "my name is $name"; #等同于"my name is peter"
字符串的运算:
1:字符串的连接:
字符串可以用'.'(点号)操作符来进行连接操作。
如:
"hello"."world" #与"helloworld"一致
$name."balabala/n" #与"$namebalabala/n"一致
注意:操作符两边的字符串都不会被改变。
例如,若要在字符串$mystr后面加"/n",则必须书写如下:
$mystr = $mystr."/n";
或 $mystr. = "/n";
2: 字符串的复制:
Perl中, 字符串复制是一个小写字母x。
它会将左边的操作数与它本身重复连接,次数为右边的操作数。
如:
"ok" x 5 #等同于"okokokokok"
3: 寻找子字符串:
Perl用index()函数来查找子字符串在字符串中最开始出现的位置;
用rindex来查找子字符串在字符串中最后出现的位置。
如:
my $ostr = "hello everyone, everyone, this is here one";
my $where1 = index($ostr, "he"); # $where1值等于 0
my $where2 = rindex($ostr, "he"); # $where2值等于 36
my $where3 = index($ostr, "I"); # $where3值等于 -1
4: 截取字符串:
substr()函数用来截取字符串中的一段子字符串:
如:
my $substr_1 = substr("hello world", 2, 5); #截取从字符串第3个字符开始的5个字符,即:"llo w"
my $substr_2 = substr("hello world", -3,3); #从字符串结尾的倒数三个字符, 截取3个字符,即:"rld";
字符串就是一连串的字符。
字符串可以包含各种字符的任意组合。
最短的字符串是空字符串(即不含字符),最长的可填满所有可用的内存。
字符串的表示形式:
在Perl中, 字符串直接量有两种表示形式:单引号内的字符串与双引号内的字符串。
1:单引号内的字符串, 单引号内的所有字符都代表它本身(单引号和反斜线除外)。
要表示反斜线或单引号,需要在它之前加一个反斜线转义, 如:
'the dir is c://temp'
'/'//' #单引号后面接着反斜线
2:双引号的字符串, 它里面的反斜线可以有一个完整的概念:
如: “hello/tworld" #hello、tab、以及world
此外, 双引号内的的字符串还具有变量替换的功能,
如:
my $name = "peter";
...
my $mystr = "my name is $name"; #等同于"my name is peter"
字符串的运算:
1:字符串的连接:
字符串可以用'.'(点号)操作符来进行连接操作。
如:
"hello"."world" #与"helloworld"一致
$name."balabala/n" #与"$namebalabala/n"一致
注意:操作符两边的字符串都不会被改变。
例如,若要在字符串$mystr后面加"/n",则必须书写如下:
$mystr = $mystr."/n";
或 $mystr. = "/n";
2: 字符串的复制:
Perl中, 字符串复制是一个小写字母x。
它会将左边的操作数与它本身重复连接,次数为右边的操作数。
如:
"ok" x 5 #等同于"okokokokok"
3: 寻找子字符串:
Perl用index()函数来查找子字符串在字符串中最开始出现的位置;
用rindex来查找子字符串在字符串中最后出现的位置。
如:
my $ostr = "hello everyone, everyone, this is here one";
my $where1 = index($ostr, "he"); # $where1值等于 0
my $where2 = rindex($ostr, "he"); # $where2值等于 36
my $where3 = index($ostr, "I"); # $where3值等于 -1
4: 截取字符串:
substr()函数用来截取字符串中的一段子字符串:
如:
my $substr_1 = substr("hello world", 2, 5); #截取从字符串第3个字符开始的5个字符,即:"llo w"
my $substr_2 = substr("hello world", -3,3); #从字符串结尾的倒数三个字符, 截取3个字符,即:"rld";