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.
-
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 How to display code and escape characters
are good places to start.