[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] working with strings



At 12.42 -0500 1999.01.22, Adam Bridge wrote:
>Lets say there is a field called full_name which is 40 characters long and
>I've
>read it into a variable $full_name.
>
>It looks like "ATKINSON, TINA                     "
>
>What I need to do is:
>
>1) reverse the name parts and
>2) have only the first character in upper case


>The way I'd think to do it in a traditional language is to find the last
>character that isn't whitespace to get the real length of the name, find the
>comma, take the characters up to the comma as the last name and the rest, save
>the leading space, as the first name.
>
>But there doesn't seem to be that sort of addressability inside strings.
>
>Probably there's a better way to do it.  Can someone suggest it?  Broad hints
>are okay.

Perl is perfect for this kind of things.  I'd probably do:

  $x = "ATKINSON, TINA                     ";
  $x =~ s/^(.+?), (.+?)\s+$/ucfirst(lc($2)) . ' ' . ucfirst(lc($1))/e;

Or:

  $x = lc("ATKINSON, TINA                     ");
  $x =~ s/^(.+?), (.+?)\s+$/\u$2 \u$1/;

But a more readable version would be:

  $x = "ATKINSON, TINA                     ";
  $x =~ s/^(.+?), (.+?)\s+$//;  # strip off trailing whitespace
                                # and capture first, last names
  $first = ucfirst(lc($2));
  $last  = ucfirst(lc($1));
  $full  = "$first $last";

Or:

  $x = "ATKINSON, TINA                     ";
  $x =~ s/^(.+?), (.+?)\s+$//;  # strip off trailing whitespace
                                # and capture first, last names
  $full = join " ", map {ucfirst(lc($_))} $2, $1;

But there are many other ways.  You could use substr and index and length,
but I would not recommend it.

Note that all of these fail where the first or last name is more than one
word (like Jim Bob Walsh).  That is a more difficult task, but this gives
you a starting point.

--
Chris Nandor          mailto:pudge@pobox.com         http://pudge.net/
%PGPKey = ('B76E72AD', [1024, '0824090B CE73CA10  1FF77F13 8180B6B6'])

***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch