Ok, be gentle, this is my first attempt at a post. I do want to learn so constructive criticism will be gladly accepted, but pointless flames will be suitably ignored. Also, this is a homework question, but I've already turned in the assignment. I'm asking to improve my skills.

First, the assignment. How would you print the first and last word of every line of input? Create a script which does that and a file to test your program on. Define a word as any sequence of \w characters. Note that the first and last word do NOT have to begin and/or end the line. There may be leading or trailing spaces or punctuation marks. These can be indicated by \W. Assume a line has at least 2 words.

So here is what I came up with for the assignment.

#!perl -w use strict; while (<>) { if (/^\W*(\w+)(\W+\w*\W*)+(\w+)\W+$/) { print "$1 $3\n"; } }

Sure, this does what the assignment asked, but I don't like it. I was hoping for some pointers on how to handle matching and ignoring the words and characters inbetween the first and last words.

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.


In reply to Matching Words by HollyKing

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.