0

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.

  • 3
    You need to think about what should happen when the user does not have one first and one last name. Examples to consider: `Johann Sebastian Bach` (2 first names), `Claus von Stauffenberg` (1 first name, last name is “von Stauffenberg”). Some names have numerals in them. In some cultures, the surname precedes the given name, e.g. `Li Xi`. Some cultures do not have surnames at all. What cases do you want to cover? – amon Sep 14 '13 at 00:58
  • The combination of `rindex()` and `substr()` is probably the most complex approach you could have chosen. Far better to go with `split()`. – Dave Cross Sep 14 '13 at 10:06

2 Answers2

3

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.

amon
  • 57,091
  • 2
  • 89
  • 149
0

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

Prem
  • 309
  • 2
  • 5
  • 11