Oesor
Oesor

Reputation: 6642

Is there a way to build an anonymous hashref from a list of slices?

When combining specific data from a couple of arrayrefs, I mapped the transformation as per the following code:

my @output_data = map {
  my $ss = $everything->{$_->{username}};
  my $distance = $gis->distance ( $_->{lat}, $_->{long} => $ss->{Latitude}, $ss->{Longitude} );
  my %data;
  @data{qw/username addr1 addr2 city state zip rec_lat rec_long/} = @{$_}{qw/username addr1 addr2 city state zip lat long/};
  @data{qw/ss_lat ss_long/} = @{$ss}{qw/Latitude Longitude/};
  $data{difference} = sprintf("%.3f", $distance->miles);
  \%data;
} @$source;

Which works. It builds a hash by adding a couple of slices from the initial data sets (which individually do not comprise the entire row, just what I care about) as well as the result of a calculation between the two. Is there a way that the ending lines can be combined cleanly into a single anonymous hashref constructor? Or would building the resulting dataset like this be the preferred way to go about it?

Upvotes: 1

Views: 90

Answers (1)

ikegami
ikegami

Reputation: 386501

You'd need something like pairwise.

use List::MoreUtils qw( pairwise );

my @output_data =
   map +{
      ( pairwise { $a => $_->{$b} }
         @{[qw( username addr1 addr2 city state zip rec_lat rec_long )]},
         @{[qw( username addr1 addr2 city state zip lat     long     )]},
      ),
      ( pairwise { $a => $ss->{$b} }
         @{[qw( ss_lat   ss_long   )]},
         @{[qw( Latitude Longitude )]},
      ),
   },
      @$source;

Upvotes: 1

Related Questions