How can I delete empty arrays/refs from a Perl hash? -


lets have following perl hash:

%hash = (      'a' => {          'b' => ['c', 'd', 'e'],          'f' => { 'g' => [], 'h' => [] },          'i' => []          } ); 

and i'd rid of []'s hash result below:

%hash = (      'a' => [         'b' => ['c', 'd', 'e'],         'f' => [ 'g', 'h', 'i' ]          ]      ) 

(i hope got {} , [] balanced, apologies if not, but) i'd make no empty arrays/ref's exist. i'm sure possible/simple, i'm not sure whether delete() work, or if there's better method or perl module out there. can steer me in right direction?

it appears data might nested arbitrarily, , want walk through recursively, rewriting patterns others. that, i'd using data::visitor.

use data::visitor::callback; use list::moreutils 'all';  $visitor = data::visitor::callback->new(     hash => sub {         ($self, $href) = @_;          # fold hashrefs empty arrayrefs values arrayrefs         if (all { ref $_ eq 'array' && !@{ $_ } } values %{ $href }) {             return [ keys %{ $href } ];         }          # strip k/v pairs empty arrayref value         return {             map {                 $_ => $href->{$_}             } grep {                 ref $href->{$_} ne 'array' || @{ $href->{$_} }             } keys %{ $href }         };     }, );  %new_hash = %{ $visitor->visit(\%hash) }; 

this illustrates basic approach i'd use, , happens work example input gave. might need various tweaks depending on want in corner-cases pointed out in other comments.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -