Perl 列表、字符串操作与正则表达式入门
1. 列表与字符串操作
在 Perl 中,列表和字符串操作是非常重要的部分,有许多内置函数可以帮助我们完成各种任务。
1.1 字符串替换示例
如果要在一个字符串中搜索并替换某个子字符串,可以使用 while 循环、 index 和 substr 函数,示例代码如下:
$str = "This is a test string. The string we want to change.";
$pos = 0;
$key = 'i';
$repl = "*";
while ($pos < (length $str) and $pos != -1) {
$pos = index($str, $key, $pos);
if ($pos != -1 ) {
substr($str,$pos,length $key) = $repl;
$pos++;
}
}
不过,使用 Perl 的正则表达式可以用更简洁的代码完成相同的任务:
$str =~ s/$key/$repl/g;
1.2 常用列表和字符串操作函数
以下是一些常用的列表和字符串操作函数:
- sort :用于对列表进行排序。
- <
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



