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:
Some optional whitespace at the start of the string.
Followed by wordy stuff and some whitespace three times.
Followed by wordy stuff that you wish to capture.
After that you don't care, it could be followed by anything.
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.