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!
This is very easy:
Output: