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; }

Cheers,
Ovid

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

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.