in reply to Converting HoA into AoH

This is my previous function rewritten to handle spaces in the data by escaping them. Other surprises may be handled similarly.

#!/usr/bin/perl use Data::Dumper; sub hoa2aoh { my $hoa = shift; my @keys = keys %$hoa; my @patterns = map { local $" = ','; "{@{[map {s/ /\\ /g; $_} @$_]}}"; } values %$hoa; [ map { my %hash; @hash{@keys} = split ','; \%hash; } glob join ',', @patterns ]; } my $HoA = { '1,2,flintstones' => [ 'fred-1 foo-2', 'barney-1 bar-2' ], '2,3,jetsons' => [ 'george-1 foo-2', 'jane-1 bar-2'], }; print Dumper hoa2aoh($HoA); __END__ $VAR1 = [ { '1,2,flintstones' => 'fred-1 foo-2', '2,3,jetsons' => 'george-1 foo-2' }, { '1,2,flintstones' => 'barney-1 bar-2', '2,3,jetsons' => 'george-1 foo-2' }, { '1,2,flintstones' => 'fred-1 foo-2', '2,3,jetsons' => 'jane-1 bar-2' }, { '1,2,flintstones' => 'barney-1 bar-2', '2,3,jetsons' => 'jane-1 bar-2' } ];

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: Converting HoA into AoH
by robin (Chaplain) on Oct 31, 2005 at 17:40 UTC

    Using glob is a delightful trick, but in general you really need to escape the string much more than this. (To see what I mean, try putting a * in one of the strings.)

    Instead of s/ /\\ /g, use s/(\W)/\\\\\\$1/g. I know it’s a lot of backslashes, but you really do need that many here!