Perl字符串函数 - 连接子字符串和分割
Perl有许多字符串函数,让我们来看看其中一些最常用的:连接、子字符串和分割。
连接
通过在字符串之间插入句号(.)运算符来连接字符串。Perl会自动将初始化为数字的标量变量转换为字符串。
# declare and concatenate two strings
my $joke = 'A horse walks ' . 'into a bar.'; # A horse walks into a bar.
# Concatenate two scalars
my $meat = 'ham';
my $bread = 'sandwich';
my $lunch = $meat . $bread; # hamsandwich
# Concatenate scalars initialised as numbers
my $hour = 6;
my $minutes = 30;
my $time_string = $hour . ':' . $minutes; # 6:30
子字符串
子字符串提取并返回现有字符串的子集。它最多接受四个参数:要提取子字符串的表达式、从何处开始提取子字符串的偏移量、子字符串的长度以及替换字符串。如果省略长度,则子字符串将运行到输入表达式的末尾。
# substr(expression, offset, [length], [replacement])
my $joke = 'A horse walks into a bar.';
my $animal = substr($joke, 2, 5); # horse
my $favourite_place = substr($joke, -4); # bar.
# Extract a substring and replace the substring in the original string
my $verb = substr($joke, 8, 5, 'runs'); # walks
print $joke; # A horse runs into a bar.
关于substr的perldoc页面有更多有用的示例。
分割
split函数使用分割模式和(可选的)分割字段数限制将输入字符串分割成一系列子字符串。如果省略输入表达式,Perl将使用$_。
# split(pattern, [expression], [number_of_fields])
my $sentence = 'A horse walks into a bar.';
my @words = split(' ', $sentence); # A,horse,walks,into,a,bar
my $fullname = 'Mr Stephen Doyle';
# Limit the split to two fields
my @title_and_name = split(' ', $fullname, 2); # Mr,Stephen Doyle
这篇文章最初发布在PerlTricks.com。
标签
反馈
这篇文章有什么问题吗?请通过在GitHub上打开问题或拉取请求来帮助我们。
LATEST COMMUNITY ARTICLES
- More commenting... maybe?
github.polettix.it - Perl Weekly Challenge 121: Invert Bit
blogs.perl.org - Web nostalgia: MojoX::Mechanize
github.polettix.it - On the eve of CPAN Testers
blogs.perl.org - PWC121 - The Travelling Salesman
github.polettix.it - PWC121 - Invert Bit
github.polettix.it - Floyd-Warshall algorithm implementations
github.polettix.it - Perl Weekly Challenge 120: Swap Odd/Even Bits and Clock Angle
blogs.perl.org - How I Uploaded a CPAN Module
blogs.perl.org - App::Easer released on CPAN
github.polettix.it