There are a couple of ways to use a regular expression to get at the data that you want to get at. Here is one that you can adapt to your particular needs.
#!/usr/bin/perl -w $_ = " one two three four "; m/\s*(\w+\s+){3}(\w+)/; $field4 = $2; print $field4;
The m stands for match and is optional but it can be good to leave it there for the sake of clarity. The match operator will by default check against the $_ variable. To generalise it you use $genvar =~ m/pattern/.

What you are searching for is something along the lines of:

  • The \w class shorthand usually stands for [a-zA-Z0-9_] so if your fields will contain anything else you will have to specify that. It can be different depending on your locale setting. Anything in brackets within the regular expression is captured into the special regular expression variables $1, $2, $3 etc and they are available to use after the expression has matched. In this case $1 would be the first three words and whatever whitespace follows them but we are not using this variable afterwards, we only use $2 which contains the fourth field when there is a match. If you know your data well then you could rely on there always being a successful match but this is unsafe coding. Even if you do know your data well you are better off assuming that something can go wrong and check using an if statement that the match did actually succeed.

    Update: I really should have used a ^ to anchor the regex to the start of the line. Otherwise it won't work properly if there are some punctuation characters at the start of the string. The regex above assumes that each line consists of only whitespace and word characters. Your mileage may vary.

    In reply to (Dermot) Re: novice by Dermot
    in thread novice by mrt

    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.