Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

(Dermot) Re: novice

by Dermot (Scribe)
on Sep 27, 2000 at 14:48 UTC ( [id://34171]=note: print w/replies, xml ) Need Help??


in reply to novice

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.

    Log In?
    Username:
    Password:

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

    How do I use this?Last hourOther CB clients
    Other Users?
    Others sharing their wisdom with the Monastery: (6)
    As of 2024-04-23 15:31 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found