perl中的字符串函数
1.
一旦我们读出了一个记录,通常打算去掉记录分隔符,(缺省值为换行符字符):
chomp($n = <STDIN>);
注: Perl 4.0版本仅有chop()操作,去掉串的最后一个字符, 不管该字符是什么。chomp() 没有这么大的破坏性,如果有行分隔符存在,它仅去掉行分隔符。如果你打算去掉行分隔符,就用chomp() 来代替chop()。
2. q//和 qq//前面一个是加单引号,后面一个是加双引号. 匹配形式是 /regex/ 而直接运行命令是( $x = `cmd`).
6.substr函数
substr函数形式如下:
$value = substr($string, $offset, $count);
$value = substr($string, $offset);
substr($string, $offset, $count) = $newstring;
substr($string, $offset, $count, $newstring); # 和前面一样
substr($string, $offset) = $newtail;
$string = "This is what you have";
# you can test substrings with =~
if (substr($string, -10) =~ /pattern/) {
print "Pattern matches in last 10 characters\n";
}
# substitute "at" for "is", restricted to first five characters
substr($string, 0, 5) =~ s/is/at/g;
# exchange the first and last letters in a string $a = "make a hat";
(substr($a,0,1), substr($a,-1)) = (substr($a,-1), substr($a,0,1));
print $a;
take a ham
7.unpack函数
# extract column with unpack
$a = "To be or not to be"; $b = unpack("x6 A6", $a); # skip 6, grab 6 print $b;
or not
chomp($n = <STDIN>);
注: Perl 4.0版本仅有chop()操作,去掉串的最后一个字符, 不管该字符是什么。chomp() 没有这么大的破坏性,如果有行分隔符存在,它仅去掉行分隔符。如果你打算去掉行分隔符,就用chomp() 来代替chop()。
2. q//和 qq//前面一个是加单引号,后面一个是加双引号. 匹配形式是 /regex/ 而直接运行命令是( $x = `cmd`).
$string = q[Jon 'Maddog' Orwant]; # literal single quotes
$string = q{Jon 'Maddog' Orwant}; # literal single quotes
$string = q(Jon 'Maddog' Orwant); # literal single quotes
$string = q<Jon 'Maddog' Orwant>; # literal single quotes
3.特殊字符包括 "\n" (新行), "\033" (八进制数的字符33), "\cJ" (Ctrl-J), "\x1B" (十六进制的字符
0x1B).
4.直接输入多行:
$a = <<"EOF"; #指明了EOF为结束符
This is a multiline here document
terminated by EOF on a line by itself
EOF
5.prinf函数
$char = chr(0x394);
$code = ord($char);
printf "char %s is code %d, %#04x\n", $char, $code, $code; # %#04x表示占四位十六进制数少的话用0补齐
charDis code 916, 0x394
6.substr函数
substr函数形式如下:
$value = substr($string, $offset, $count);
$value = substr($string, $offset);
substr($string, $offset, $count) = $newstring;
substr($string, $offset, $count, $newstring); # 和前面一样
substr($string, $offset) = $newtail;
$string = "This is what you have";
# you can test substrings with =~
if (substr($string, -10) =~ /pattern/) {
print "Pattern matches in last 10 characters\n";
}
# substitute "at" for "is", restricted to first five characters
substr($string, 0, 5) =~ s/is/at/g;
# exchange the first and last letters in a string $a = "make a hat";
(substr($a,0,1), substr($a,-1)) = (substr($a,-1), substr($a,0,1));
print $a;
take a ham
7.unpack函数
# extract column with unpack
$a = "To be or not to be"; $b = unpack("x6 A6", $a); # skip 6, grab 6 print $b;
or not