http://www.perlmonks.org?node_id=970125

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' );

Replies are listed 'Best First'.
Re: building a hash from regex matches
by NetWallah (Canon) 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;