Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
Assuming that the data is in a file called "data.txt", I might try something like the following (untested):
#!/usr/bin/perl -w use strict; my %somehash; my $file = 'data.txt'; open FILE "<$file" or die "Can't open $file for reading: $!"; while (<FILE>) { if (/^(\d+)\s+[^\s]+\s+[^\s]+\s+([a-zA-Z]+)$/ { $somehash{$2} = $1; } }
The regex breaks out as follows:
/^ # Anchor to beginning of string ( # Capture to $1 \d+ # one or more digits ) # \s+ # One or more whitespace [^\s]+ # One or more non-whitespace \s+ # One or more whitespace [^\s]+ # One or more non-whitespace \s+ # One or more whitespace ( # Capture to $2 [a-zA-Z]+ # One or more letters ) # $/x; # Anchor to end of string
For more information about why I did not use a simpler regex like /^(\d+).*\b(\w+)$/, you may want to read Death to Dot Star!.

Simpler, however, would be to use a split (also untested):

while (<FILE>) { chomp; my ($value, $key) = (split /\s/, $_)[0,3]; $somehash{$key} = $value; }


Update: I would just like to say that I have no frickin' idea why I wrote that regex. Yes, it works. So what? I saw regex in the title and got carried away.

Use the split;

UpdateII: Yup. I have the key value backwards. It's fixed now. Sigh.

Join the Perlmonks Setiathome Group or just go the the link and check out our stats.

In reply to (Ovid) Re: regexp's by Ovid
in thread regexp's by djw

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2022-08-13 21:21 GMT
Find Nodes?
    Voting Booth?

    No recent polls found