[tpm] Breaking a string up into hash keys

Uri Guttman uri at stemsystems.com
Sun Apr 14 08:43:46 PDT 2013


On 04/14/2013 08:53 AM, Olaf Alders wrote:

> use Hash::Flatten qw( flatten );

you don't need that module if you just use a very obscure but valid perl 
trick call multidimensional hashes. this is from old perl4 days but 
still works. if you use a list as the key in a scalar hash lookup, the 
list is joined with $; (see perlvar) and used as a single key. $; 
defaults to "\034" which is not printable. note that that value is 
unlikely to be in any printable key so the joined string will be unique 
and work as a flat hash key.

so all you need to do is use that trick to generate the single level 
hash and also to access it.
>
> my $key = 'this::and::the::other::thing';
> $key =~ s/::/./g;

instead of s/// just do a split on ::

	my @keys = split /::/, $keys ;

	$flat{ @keys } = 'foo' ;

if that doesn't work because the array is put into scalar context, you 
can do the join directly:

	$flat{ join $;, @keys } = 'foo' ;

and stay away from string eval for any normal data manipulation. it is 
slow and dangerous and actually rarely needed. it is NOT needed here at all.

uri



More information about the toronto-pm mailing list