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

RE: [FWP] Fun With Golf




Joey Mitchell Comeau [mailto:aw096@chebucto.ns.ca] said:
: > >  Write a Perl subroutine which returns the fifth word in 
: a string. A word
: > >  is any sequence of letters, numbers, and/or underscores. 
: The string will
: > >  be passed as the sole argument and will contain at least 5 words.
: > 
: > Here's my try.  Start AFTER the opening {, please.
: > 
: >   sub fifth_word {my$a=pop;s/(\w+)// for 1..5;$1}
: >             start^                              ^end
: 
: Here's mine.
: 

Yours will return an empty string on input like "This is a test. This is
only a test." because the space and period *both* qualify for /\W/. However,
I like it; it's a good start. Here're some s[h]avings, stealing an idea or
two:

:       sub fifth($) {(split(/\W/,shift))[4]};
        sub fifth($) {(split/\W+/,pop)[4]}

The pop() (courtesy of Jeff Pinyan) is shorter than either shift() or
another option, $_[0]. The parens around the split() args can be
eliminiated. \W+ will deal with multiple non-word characters (like a period
and a space) as expected.

Back to work ...

Regards,
Eli

-- 
Eli Evans, Libronix Corp
www.libronix.com - eli@libronix.com
"Put 30 kids in a room with an easel,
a computer, and a guitar. You'll get
one Van Gogh, one Von Neumann, and one
Van Halen (or Van Morrison). And 27
burger flippers."---Damian Conway



==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe