Assuming the name contains exactly one surname which cointains no spaces, and an arbitrary number of first names, we can do this:
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";
Always use strict; use warnings;
to get as much error reports as possible. If you ignore them you likely have a bug. It also forces you to declare all variables.
Functions like rindex
and index
are rarely used in Perl. Regexes are often a more expressive alternative. We could also have done:
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";
That regex means: ^
anchor at the start of the string, (.*)
consume and remember as many characters as possible, \s+
match one or more whitespace characters, (\S+)
consume and remember one or more non-whitespace characters, $
anchor at line end.