mc_prakash has asked for the wisdom of the Perl Monks concerning the following question:

Hi Perl Gurus
I have contents of a hash table inform of a lengthy string as follows "{key_1 : value_1}{key_2 : value_2}.....{key_n : value_n}" I want to convert this back to hash table in few steps. Right now i remove the first/last character. Split by "}{" and each element of split array is again split by ":" and then pushed into a new hash table. Is there a simpler and easier way to do this? thanks Prakash

Replies are listed 'Best First'.
Re: converting a String to Hashtable
by johngg (Canon) on Nov 10, 2009 at 11:39 UTC

    A global match and a split in a map.

    $ perl -Mstrict -MData::Dumper -wle ' > my $string = q{{key_1 : value_1}{key_2 : value_2}{key_n : value_n}}; > my %hash = map split( m{\s*:\s*} ), > $string =~ /{([^}]+)/g; > print Data::Dumper->Dumpxs( [ \ %hash ], [ qw{ *hash } ] );' %hash = ( 'key_1' => 'value_1', 'key_2' => 'value_2', 'key_n' => 'value_n' ); $

    Cheers,

    JohnGG

Re: converting a String to Hashtable
by AnomalousMonk (Archbishop) on Nov 10, 2009 at 08:39 UTC
    Essentially like the others, but maybe slightly simpler:
    >perl -wMstrict -le "my $s = '{key_1 : value_1}{key_2 : value of 2} {key n : 0}'; my $spl = qr{ \s* [{}:] \s* }xms; my %hash = grep length($_), split $spl, $s; use Data::Dumper; print Dumper \%hash; " $VAR1 = { 'key_1' => 'value_1', 'key_2' => 'value of 2', 'key n' => '0' };
    The grep is needed to filter out spurious zero-length sub-strings produced by the split regex, so you can't have a key or value that is a zero-length string. Note that embedded spaces are preserved within key and value sub-strings, but leading and trailing spaces are stripped.
Re: converting a String to Hashtable
by bichonfrise74 (Vicar) on Nov 10, 2009 at 06:28 UTC
    Try this.
    #!/usr/bin/perl use strict; my %record; my $string = "{key_1 : value_1}{key_2 : value_2}{key_n : value_n}"; for ( map { split /\}/ } $string ) { $record{$1} = $2 if /\{(\w+)\s:\s(\w+)/; }
Re: converting a String to Hashtable
by colwellj (Monk) on Nov 10, 2009 at 05:32 UTC
    Prakash,
    I can't think of a quicker way off hand but your query does beg the question.
    Why did your hash end up in a string in the first place?
    If you need to work on it, inside the hash might be simpler in the long run
    John
      I get input string from a file. It was stored that way by some previous programmer.
Re: converting a String to Hashtable
by Anonymous Monk on Nov 10, 2009 at 06:29 UTC
    That looks very much like JSON, so use JSON;