Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

building a hash from regex matches

by polarbear (Novice)
on May 12, 2012 at 01:37 UTC ( #970125=perlquestion: print w/ replies, xml ) Need Help??
polarbear has asked for the wisdom of the Perl Monks concerning the following question:

I have an array of strings which I need to parse to get key value pairs to build a hash. The code I use works but I feel there must be a more efficient way. If this has been answered already then my google-fu is weak on the subject.

#!/usr/local/bin/perl -w use Data::Dumper; my @lines = ( 'lukeskywalker 444-333-2974 A sum 20.0860 ZYX-237', 'austinpowers 57240437 ZQFMR sum 21.3820 HRM4922', 'jedclampet HNG-47255 MLP92 sum 14.2043 QRZ4993' ); my %data; foreach (@lines) { /^(\w+).*?sum\s+([0-9.]+)/; $data{$1} = $2; } print Data::Dumper->Dump([\@lines, \%data], ["*lines", "*data"]); Output @lines = ( 'lukeskywalker 444-333-2974 A sum 20.0860 ZYX-237', 'austinpowers 57240437 ZQFMR sum 21.3820 HRM4922', 'jedclampet HNG-47255 MLP92 sum 14.2043 QRZ4993' ); %data = ( 'lukeskywalker' => '20.0860', 'austinpowers' => '21.3820', 'jedclampet' => '14.2043' );

Comment on building a hash from regex matches
Download Code
Re: building a hash from regex matches
by NetWallah (Abbot) on May 12, 2012 at 04:11 UTC
    Not any more efficient, but can be written as a single line:
    my %data2= map {/^(\w+).*?sum\s+([0-9.]+)/} @lines;

                 I hope life isn't a big joke, because I don't get it.
                       -SNL

      Also as:

      my %data2 = "@lines" =~ /^(\w+).*?sum\s+([0-9.]+)/mg;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://970125]
Approved by ww
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (11)
As of 2015-07-06 15:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (77 votes), past polls