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;

I am Dong B. Calmada, a.k.a. dungkal, and this is my public journal. I am tackling here a pot pourri of topics ranging between travails and triumphs, between observations and truths, in my life as an advocate for real development, family man and 













[...] can add an entry and look in it for particular words I’d like to retrieve. Then, as I posted here, I created a script to automagically rearrange a list of disordered names according to [...]
Making things easy through Perl « Activism 102
October 3, 2007 at 4:16 am