假设这个名字只包含一个不包含空格的姓氏和任意数量的名字,我们可以这样做:
use strict; use warnings; use feature 'say';
chomp(my $full_name = <>); # read a name
my @names = split ' ', $full_name; # split it at spaces
my $last_name = pop @names; # remove last name from the @names
my $first_name = join ' ', @names; # reassemble the remaining names
say "First name: $first_name"; # say is print that always appends a newline
say "Last name: $last_name";
say "Last, first: $last_name, $first_name";
总是use strict; use warnings;
尽可能多地获得错误报告。如果你忽略它们,你可能有一个错误。它还强制您声明所有变量。
Perl 中很少使用类似rindex
和的函数。index
正则表达式通常是一种更具表现力的选择。我们也可以这样做:
use strict; use warnings; use feature 'say';
chomp(my $full_name = <>);
my ($first_name, $last_name) = $full_name =~ /^(.*)\s+(\S+)$/;
say "First name: $first_name";
say "Last name: $last_name";
say "Last, first: $last_name, $first_name";
该正则表达式意味着:^
锚定在字符串的开头,(.*)
使用并记住尽可能多的字符,\s+
匹配一个或多个空白字符,(\S+)
使用并记住一个或多个非空白字符,$
锚定在行尾。