in reply to Re: Persistent data structures -- why so complicated?
in thread Persistent data structures -- why so complicated?

Thanks! I think I got freaked out by the Perl Cookbook's lengthy example as to how to use file locking with Storable, but now that I've looked at the outstanding documentation for the module I see there's even a lock_store function (and lock_nstore for a more portable though slightly slower solution) that apparently would replace those details (and lock_retrieve). Sometimes the Cookbook (2003) tells me more than I need to know, but Time Marches On and I forget that the state of the art is different than when the second edition of the Cookbook was published 18 years ago. It's still the book I typically reach for first.

Would a comma-separated data format work in my example? Each student "record" has a key that holds multiple values (the student's hobbies), so I'm thinking there isn't a key-to-scalar-value relationship that's required for a CSV format.

  • Comment on Re^2:Persistent data structures -- why so complicated?

Replies are listed 'Best First'.
Re^3: Persistent data structures -- why so complicated?
by Tux (Canon) on Mar 12, 2021 at 08:34 UTC

    Of course CSV would suffice for the example you gave, but it will be a lot more complicated if you have nested structures.

    You can combine all the given examples, e.g. use the Database example by using DBD::CSV or next level, tie that CSV database handle with Tie::Hash::DBD and use your hash without changing the rest of your program.

    One advice: don't underestimate how "simple" CSV is. *do* use a module, like Text::CSV_XS and/or Text::CSV.

    For the hobbies, you would either require a serialization like Sereal or Storable.

    If hobbies is the *only* field with multiple values, just drop them at the end of the record, so you can restore them lik

    use 5.14.2; use warnings; use Text::CSV_XS "csv"; use Data::Peek; my $data = csv (in => *DATA); my @hdr = @{shift @$data}; my $n = $#hdr; my @students = map { my %h; @h{@hdr} = splice @$_, 0 , $n; $h{hobbies} = [ @$_ ]; \%h, } @$data; DDumper \@students; __END__ name,home_town,age,hobbies Angie Green,Denver,12,Horses,Painting,Karaoke,Ham Radio Jamie Brown,London,34 Mark White,Madrid,56,Cooking,Perl,Running Mary Black,Dublin,30,Baking,Singing,Swimming,Programming Perl

    -->

    [ { age => '12', hobbies => [ 'Horses', 'Painting', 'Karaoke', 'Ham Radio' ], home_town => 'Denver', name => 'Angie Green' }, { age => '34', hobbies => [], home_town => 'London', name => 'Jamie Brown' }, { age => '56', hobbies => [ 'Cooking', 'Perl', 'Running' ], home_town => 'Madrid', name => 'Mark White' }, { age => '30', hobbies => [ 'Baking', 'Singing', 'Swimming', 'Programming Perl' ], home_town => 'Dublin', name => 'Mary Black' } ]
    use Text::CSV_XS "csv";

    Enjoy, Have FUN! H.Merijn