Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you map an array [key1,val1] to a hash { key1 => val1} in perl?

The problem is I have an array that has the key value pairs as elements in an array and I have to split them up somehow into key => value pairs in a hash.

my first attempt at this works, but I think its pretty messy - I have to get every other element of the arrays, and then filter through to find the accepted keys to create a hash with

my $HASH;
my $ARRAY = [ key1, val1, key2, val2, __key3__, val3, __key4__, val4 ];
   my @keys = map{ $ARRAY[ $_*2   ] } 0 .. int($#ARRAY/2);
   my @vals = map{ $ARRAY[ $_*2+1 ] } 0 .. int($#ARRAY/2);

   my $i = 0;
   #filter for keys that only have __key__ format
    for $key (@keys){
      if( $key && $key =~ m/^__(.*)__$/i ){
       $HASH{$1} = $vals[$i];
      }
     $i++;
    }
   # only key3 and key4 should be in $HASH now

I found this sample code which I think is close to what I'm looking for but I cant figure out how to implement something similar over an array rather than iterating over lines of a text file:

$file = 'myfile.txt'
open I, '<', $file
my %hash;
%hash = map { split /\s*,\s*,/,$_,2 } grep (!/^$/,<I>);
print STDERR "[ITEM] $_ => $hash{$_}\n" for keys %hash;

Can any of you perl gurus out there help me understand the best way to do this? Even if I could somehow join all the elements into a string then split over every second white space token -- that might work too, but for now Im stuck!

like image 511
qodeninja Avatar asked Nov 28 '22 18:11

qodeninja


2 Answers

This is very easy:

use strict; use warnings;
use YAML;

my $ARRAY = [qw(key1 val1 key2 val2 __key3__ val3 __key4__ val4)];
my $HASH =  { @$ARRAY };

print Dump $HASH;

Output:

C:\Temp>
---
__key3__: val3
__key4__: val4
key1: val1
key2: val2
like image 71
rouzier Avatar answered Dec 10 '22 03:12

rouzier


my $ARRAY = [ qw(key1 val1 key2 val2 key3 val3 key4 val4) ];
my $HASH = { @$ARRAY };
like image 27
Keith Thompson Avatar answered Dec 10 '22 03:12

Keith Thompson