Perl solution: Sorting disordered names

Problem: You got a list of names which start with firstname and which is disordered. Worse, each line starts with a string “> “.

Objective: Rearrange the names so that the lastname goes first with the indent string (”> “) gone.

Perl Solution:

#!/usr/bin/perl -w
#
# Context:
# The source file contains lines like these:
# > Dong Calmada
# > Zaldy Pineda
# > Jijo Fernandez III
# > Martin Howell Banares
#
# You want to sort the lines according to lastname, with the indent symbol gone.
#
use strict;

my $lname = “”;
my $fname = “”;
my @names = ();
my $name = “”;
my $name_compare = “”;

open SOURCE, “/path/to/source/file”;
open TARGET, “>/path/to/new/target/file”;

while (<source>) {
if (m/^\> ([a-zA-Z]+) ([a-zA-Z]+) ([a-zA-Z]+) ([a-zA-Z]+)$/) {
if ($4 eq ‘II’ | $4 eq ‘III’ | $4 eq ‘Jr’) {
$fname = $1 . ” ” . $2 . ” ” . $4;
$lname = $3;
} else {
$fname = $1 . ” ” . $2 . ” ” . $3;
$lname = $4;
}
} elsif (m/^\> ([a-zA-Z]+) ([a-zA-Z]+) ([a-zA-Z]+)$/) {
if ($3 eq ‘II’ | $3 eq ‘III’ | $3 eq ‘Jr’) {
$fname = $1 . ” ” . $3;
$lname = $2;
} else {
$fname = $1 . ” ” . $2;
$lname = $3;
}
} elsif (m/^\> ([a-zA-Z]+) ([a-zA-Z]+)$/) {
$fname = $1;
$lname = $2;
}
$name = $lname . “, ” . $fname;
push(@names, $name);
}

@names = sort @names;

foreach $name (@names) {
if ($name_compare ne $name) {
print TARGET $name . “\n”;
}
$name_compare = $name;
}

close SOURCE;
close TARGET;

Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s