I'm trying to take a person's full name, "Firstname Middlename Lastname" and invert it to "Lastname, Firstname Middlename". I'm reading in a file and trying to write out to a sql script.

Here is the data:

Literature|30001f3d|John M. Doe

This is what I'm trying to get:

INSERT INTO Books Title,FileID,author,authInv) VALUES ('Literature','30001f3d','John M. Doe','Doe, John M.');

I'm new to perl so I don't know how to write a script to invert it. I've seen a code before where you take the full name, start the counter at the end, go until you hit a space and reformat the field to add the comma but I just can't make it work. Any help would be appreciated. Thanks.

Here is the code:

print "What is the directory where we'll be working: "; $directory = <STDIN>; chomp ($directory); print "What is the file name, with a file extension: "; $file = <STDIN>; chomp ($file); $originalfile = "$directory/$file"; open(FIRST, "<$originalfile" ) || die "I cannot open $originalfile. $! +"; @contents = <FIRST>; close(FIRST); $new = "$directory/SQL-Insert-Titles.sql"; unlink($new); open(SECOND, ">$new") || die "I cannot open $new. $!"; foreach $line (@contents) { @splitline = split /\|/, $line; $title = $splitline[0]; $file = $splitline[1]; $author = $splitline[2]; $authinv = $splitline[3]; chomp($title); chomp($file); print SECOND "INSERT INTO Books Title,FileID,author,authInv) VALUES ('$title','$file','$author','$authinv')\;\n"; } close(SECOND); print "\n\tDone."; |
Edited 2005-04-08 by Ovid

In reply to Inverting full names by kieps

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.