in reply to Re: Storing/parsing perl data structure in/from a file
in thread Storing/parsing perl data structure in/from a file

Thanks for you answer ! My data structure is actually 6-7 levels deep and I got it to work with arrays of hashes of arrays of ... hashes. I want to know if it's possible to `do` a file partially, or open a file and manually parse each line and then `do` whatever part I want to. Anyways, I will work with arrays for now.
  • Comment on Re^2: Storing/parsing perl data structure in/from a file

Replies are listed 'Best First'.
Re^3: Storing/parsing perl data structure in/from a file
by LanX (Saint) on Jun 12, 2013 at 23:40 UTC
    Plz note: the data you posted is not a valid serialization of a HoH!

    The only way I see is to assign the data to a tied hash, which automatically reacts on collisions...of course all nested hashes need to be tied too.

    something like

    my $datastring =slurp $file; tie %h, "CollisionHash"; eval "\%h = $datastring"
    Not sure of this works, and I don't wanna trie to implement it for such a "unique" requirement...

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      As I feared (though it makes sense)

      tied_hashes do it with list assignments (they are sequential) but not with ano-hash assignment (they are precompiled, hence collisions are optimized)

      FWIW

      use strict; use warnings; use Data::Dump qw/pp/; package HoA; require Tie::Hash; our @ISA = qw(Tie::StdHash); sub STORE { my ($this,$key,$value) =@_; push @{$this->{$key}}, $value; } package main; my $data_str= do { local $/;<DATA>}; tie my %h, "HoA"; my $h=\%h; %h = eval "$data_str"; pp $h; %h = eval "%{ { $data_str } }"; pp $h; __DATA__ ( alpha => 1, alpha => 2 )

      shows

      { # tied HoA alpha => [1, 2], } { # tied HoA alpha => [2], }

      Cheers Rolf

      ( addicted to the Perl Programming Language)

Re^3: Storing/parsing perl data structure in/from a file
by frozenwithjoy (Priest) on Jun 12, 2013 at 23:33 UTC
    You're welcome. What exactly do you mean when you say "`do` a file"?
      I mean, when I do `do $file`, Perl would read the entire data structure at once and overwrite hash keys with the last value it reads. I wish there was a way for me to traverse through the data structure (which Perl would be doing internally to be able to find key collisions) manually.
        It's correct that do file means slurp + eval but your data only defines an anonymous hash on the top level.
        { alpha => { beta => { gamma => theta, delta => lambda, }, beta => { gamma => zeta, }, }, },

        you need to add a variable name!

        Cheers Rolf

        ( addicted to the Perl Programming Language)