in reply to Hash/Array slice : how to exclude items?
very interesting question and discussion. I am not able to offer a solution but this lead to me to something different: temporary hide or mask the value of some key of a tied hash.
Mostly copying ikegami's SO answer I got something working.
I'm sure some monk can play also with FIRTSKEY and NEXTKEY vodoo to make some key temporary invisible (see the comment line in fetch..), not me :)
package MaskKeys; use strict; use warnings; use Tie::Hash (); our @ISA = 'Tie::ExtraHash'; sub TIEHASH { my $class = shift; my $content = shift; my $tomask = shift; my $self = bless([{@$content}, {}]); $self->[1]{$_} = 1 for @$tomask; return $self; } sub FETCH { my $self = shift; my $key = shift; if ( $self->[1]{$key} ){ return 'NA'; # {return $self->{ $self->FETCH($self->SUPER::NEXTKEY ($ke +y))} || undef ; } else { return $self->[0]{$key} } } sub mask_key{ my $self = shift; my $key = shift; $self->[1]{$key} = 1; } sub unmask_key{ my $self = shift; my $key = shift; # delete @{ $self->[1] }{ $key }; unecessary from cut and paste co +de that accepted a list delete $self->[1]{$key}; } package main; # content # to mask tie my %hash, 'MaskKeys',[schema=>11111, aaaaaa=>33333], ['schema']; print "\noriginally masked: \n"; print "$_ -> $hash{$_}\n" for keys %hash; print "\nunmasked: \n"; tied(%hash)->unmask_key('schema'); print "$_ -> $hash{$_}\n" for keys %hash; print "\nmasked again: \n"; tied(%hash)->mask_key('schema'); print "$_ -> $hash{$_}\n" for keys %hash; __END__ originally masked: aaaaaa -> 33333 schema -> NA unmasked: aaaaaa -> 33333 schema -> 11111 masked again: aaaaaa -> 33333 schema -> NA
L*
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Hash/Array slice : how to exclude items? -- tie hash to mask values
by bliako (Abbot) on Jan 26, 2023 at 15:06 UTC |