Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

(Ovid) Re: regexp's

by Ovid (Cardinal)
on Oct 03, 2000 at 06:20 UTC ( #35039=note: print w/replies, xml ) Need Help??


in reply to regexp's

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.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (2)
As of 2022-08-13 22:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?