Search code examples
perlperl-data-structures

How to slice only defined values?


I can slice kes/values as next:

$item->%{ @cols }

But if some column does not exist at $item It will be created at resulting hash.

Can I slice only defined values?


Solution

  • You can check whether they exist.

    $item->%{ grep {exists $item->{$_}} @cols }
    

    should do the job slicing only the existing values.

    Anyway - simply accessing these values should NOT autovivify them. Only if you Pass these values as parameters to some function and they are implicetly aliased there, they are autovivified.

    use strict;
    use warnings;
    use Data::Dumper;
    
    my @cols =qw (a b c);
    my $item = [{a => 1, c => 3}];
    
    print Dumper({$item->[0]->%{ grep {exists $item->[0]->{$_}} @cols }});
    print Dumper($item);
    
    print Dumper({$item->[0]->%{ @cols }});
    print Dumper($item);
    
    print Dumper($item->[0]->%{ grep {exists $item->[0]->{$_}} @cols });
    print Dumper($item);
    
    print Dumper($item->[0]->%{ @cols }); ## Only here does autovivication take place
    print Dumper($item);
    

    Only the last print will generate the:

    $VAR1 = [
              {
                'c' => 3,
                'a' => 1,
                'b' => undef
              }
            ];
    

    indicating that b got autovivified.