I'm pretty new at Perl. I have to have the user enter their full name and then print just the first, just the last, and the in "last, first" format.

I basically just have

chomp ($name = <\STDIN>);

so far. And a bunch of stuff that hasn't worked. Ignore the '\' in the STDIN, this is my first post and I couldn't figure out formatting.

Solved:

chomp ($name = <STDIN>);
$first = substr $name, 0, rindex($name, ' ');
$last = substr $name, (rindex($name, ' ')+1);
print "\nFirst Name: ".$first;
print "\nLast Name: ".$last;
print "\nLast, first: ".$last.", ".$first;

Got it figured out with some better google searches.

2

There are 2 best solutions below

0
On

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.

0
On

Please read perl split function .

my $data = <STDIN> 
my @values = split(' ', $data);
my $first = $values[0];
my $last = $values[1];

I hope this could help