Weekly Perl Script [Issue 7]

j proctor jproctor at oit.umass.edu
Fri Jul 23 07:36:15 CDT 1999


On the Jax.PM jacksonville-pm-list;
j proctor <jproctor at oit.umass.edu> wrote -



Okay, no one has answered in a week.  I guess I'll stab at it.


>  while (++$len <= length) {
>       print substr($_, $len, 1)
>           if (index("abcdefghijklmnopqrstuvwxyz",
>                      substr($_ , $len, 1)) > -1);
>   }

Working from the assumption that this is the significant part of the
program you were asking us to replace (even though a few of those other
lines are extraneous), and you like the output format, and whatever else
I'm not addressing by simply removing the rest of the code, here's what I
found, given the constraint that we had to use split:

There's More Than One Way To Do It.(tm)

In my first attempt, I went for the fairly straightforward "split it into
characters and print each character if it's a lowercase letter".  While
there are many many ways to write this in Perl, I decided to try my hand
at the map function.  The code above can be replaced by

map { /[a-z]/ && print } split('', $_);

However, that still required the test of every character.  So, I thought
about the problem from a slightly different angle.  What I really wanted
to do was throw away everything that wasn't [a-z] and print what was left.
My first thought along this line was tr/a-z//cd, but that didn't involve
splitting anything.  Split.  Split.  What does split do?  Split takes a
string or regex and treats it as a delimiter to apply to a scalar
(usually a string), thereby spitting out a list of things in that scalar
that were separated by that delimiter.  

*** And it throws away the delimiter! ***

So all I had to do is make a regex for the parts I wanted to keep, then
split using <everything else> as the delimiter.  So, my final answer is to
replace the code above by

print split(/[^a-z]+/, $_);


For the second (bonus) question, what's so 'funny' about the script, I
have no idea.  The bits where he strips white-space aren't necessary, but
I don't feel like running benchmarks to see if they actually hurt
performance.  It's at least slightly amusing that sneex put the effort
into playing with this when the whole thing could by handled by that tr///
I wrote a couple paragraphs above, and that I was duped into playing with
it also.  I did use map for the very first time, so it wasn't a total
loss. :)

Um, I can't think of anything else.  What, pray tell, was so 'funny'?


j



The Jacksonville Perl Monger's Group is operated by -
Bill -Sneex- Jones ( sneex at usa.net ),
to whom send all praises, complaints, or comments...




More information about the Jacksonville-pm mailing list