http://www.perlmonks.org?node_id=1002862

vinoth.ree has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks

I need to read a file which contains the hash reference

#------------------- #Conf File #-------------------- { "one" => { 1 => "one", 2 => "two", 3 => { "inner" => "value", "inner" => "value" } }, "2" => { 1 => "one", 2 => "two", }, "two" => { 4 => "test", 3 => "test1", } }

I read this file using the do(), but I am not getting the same order of file content as it is, I should get in Order how to do it?

I am getting like below

$VAR1 = { 'one' => { '1' => 'one', '3' => { 'inner' => 'value' }, '2' => 'two' }, 'two' => { '4' => 'test', '3' => 'test1' }, '2' => { '1' => 'one', '2' => 'two' } };
Any Idea Please.Thanks In Advance.

Update: Updated the question.

Replies are listed 'Best First'.
Re: Read Hash reference from File
by Anonymous Monk on Nov 08, 2012 at 10:13 UTC

    I read this file using the do(), but I am not getting the same order of file content as it is

    Any Idea Please.Thanks In Advance.

    This is FAQ, hashes do not guarantee order

Re: Read Hash reference from File
by jethro (Monsignor) on Nov 08, 2012 at 11:34 UTC
    If you need order, use arrays. Or if hashes are just to convenient for the data, add an order counter to the data and sort the references into an array. This array can be created after you have read in the hash, kept alongside the hash in memory and is valid as long as the hash doesn't change.
Re: Read Hash reference from File
by nagalenoj (Friar) on Nov 08, 2012 at 11:50 UTC
    Back into perlmonks after a long time. :)

    Seems interesting. Since you don't want the order to be changed, I think you can try with PPI.

    Here is a sample code, which I tried. You can make it better for your use.

    use PPI; my $ds = PPI::Document->new('sample_config.pl'); for my $sub ( @{ $ds->find('PPI::Statement::Expression') || [] } ) { my $Tokenizer = PPI::Tokenizer->new( \$sub ); while ( my $Token = $Tokenizer->get_token ) { print "Found token '$Token'\n" if ( $Token =~ /\w+/ ); } print "---------------------------------------------\n" }

    Hope it helps. Thanks.