in reply to Re: Problem in printing lastname and firstname
in thread Problem in printing lastname and firstname
In the same vein I'd advise the OP to constrain the scope of his variables to make it easier to see where they are used and to avoid the bogus initialisations.
Always initialising variables seems like a good idea, but is only appropriate where the variable is being given a default value. If it is intended that the initial value will always be replaced, it is much better not to provide a bogus intial value. Perl's use warnings; "undef used" warning gives an immediate heads up that there is a path or condition in your code that you hadn't anticipated is you leave variables uninitialised until you have a sensible value for them.
Reworking the code again with that in mind and after fixing various issues that arise during testing you might end up with:
#!/usr/bin/perl use strict; use warnings; my @nme; # Input loop while ((print "Enter the name: "), defined (my $input = <STDIN>)) { chomp $input; last if ! length $input; # Exit loop on empty line my ($fn, $ln) = split /\s+/, $input, 2; if (! defined $fn) { print "Blank name ignored\n"; next; } $ln ||= '_missing_'; # Provide missing name print "$fn, $ln\n"; push @nme, "$ln, $fn"; } # Print loop print "$_\n" foreach sort @nme;
Note too the use of the comma operator in teh while loop expression to get the prompt output each time through the loop. Not a highly recommended technique, but can be less ugly and more cogent than many of the alternative ways of achieving the same effect.
Note too that the hash changed into an array. It's quite possible for two people to have the same last name. In fact it is even possible for people to have the same name. Names are tricky. ;)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Problem in printing lastname and firstname
by johngg (Canon) on Nov 19, 2006 at 00:25 UTC |