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.
Assuming the name contains exactly one surname which cointains no spaces, and an arbitrary number of first names, we can do this:
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
andindex
are rarely used in Perl. Regexes are often a more expressive alternative. We could also have done: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.