Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Matching Words

by Zaxo (Archbishop)
on May 23, 2002 at 06:28 UTC ( [id://168679]=note: print w/replies, xml ) Need Help??


in reply to Matching Words

How about this?

#!perl -w use strict; while (<>) { my @words = split /\W+/; pop @words if $words[-1] eq ''; # pop @words unless $words[-1]; shift @words if $words[0] eq ''; # shift @words unless $words[0]; print $words[0], ' ', $words[-1], $/; }
The pop and shift are needed because split leaves empty elements at the ends if nonword characters are there.

A couple of comments on your code. I think you mean \W*$/ at the right of your regex. Also, you can use a (?:\W+\w*\W*)+ to get grouping without capture.

Update: I sure like MeowChow's array slice in print:

print "@words[0,-1]$/";

Update 2: A palpable hit, ++tadman. Corrected.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: Matching Words
by tadman (Prior) on May 23, 2002 at 07:34 UTC
    In:
    0 donuts are in the drawer on the left
    Out:
    donuts left
    If zero were true, then black would be white, and you would likely be killed by a bus when using a zebra crossing. Or so I have heard.

    New riff based on MeowChow's direction:
    perl -ple '$_="@{[/\w+/g]}[0,-1]"'
    Homework, Golf, what's the difference?
      Homework, Golf, what's the difference?

      The teacher's ability to comprehend the answer, I would guess :-)

      ps. nice stroke.

         MeowChow                                   
                     s aamecha.s a..a\u$&owag.print
Re: Re: Matching Words
by HollyKing (Pilgrim) on May 23, 2002 at 16:20 UTC

    Ahh, yes it should be \W*$ at the end.

    Owl looked at him, and wondered whether to push him off the tree; but, feeling that he could always do it afterwards, he tried once more to find out what they were talking about.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://168679]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2024-04-26 01:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found