Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl6 equivalent of Perl's 'store' or 'use Storable'

Tags:

raku

I am attempting to write a hash, which is written very slowly, into a data file, but am unsure about how Perl6 does this in comparison to Perl5. This is a similar question Storing intermediate data in a file in Perl 6 but I don't see how I can use anything written there, specifically messagepack.

I'd like to see the Perl6 equivalent of

my %hash = ( 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
use Storable;
store \%hash, 'hash.pldata';

and then read with

my $hashref = retrieve('hash.pldata');
my %hash = %{ $hashref };

This is built in to Perl5, it's super easy, I don't need to install any modules (I love it!), but how can I do this in Perl6? I don't see it in the manual. They appear to be talking about something else with STORE https://docs.perl6.org/routine/STORE

like image 626
con Avatar asked Jan 31 '19 16:01

con


2 Answers

How about this? OK, not as efficient as Storable but it seems to work....

#!/usr/bin/perl6
my $hash_ref = {
    array  => [1, 2, 3],
    hash   => { a => 1, b => 2 },
    scalar => 1,
};

# store
my $fh = open('dummy.txt', :w)
    or die "$!\n";
$fh.print( $hash_ref.perl );
close($fh)
    or die "$!\n";

# retrieve
$fh = open('dummy.txt', :r)
    or die "$!\n";
my $line = $fh.get;
close($fh)
    or die "$!\n";

my $new_hash_ref;
{
    use MONKEY-SEE-NO-EVAL;
    $new_hash_ref = EVAL($line)
        or die "$!\n";
}

say "OLD: $hash_ref";
say "NEW: $new_hash_ref";

exit 0;

I get this

$ perl6 dummy.pl
OLD: array      1 2 3
hash    a       1
b       2
scalar  1
NEW: array      1 2 3
hash    a       1
b       2
scalar  1
like image 110
Stefan Becker Avatar answered Nov 10 '22 01:11

Stefan Becker


While these do not directly match Storable, there are a couple of approaches outlined at:

  • http://perl6maven.com/data-serialization-with-json-in-perl6
  • https://perl6advent.wordpress.com/2018/12/15/day-15-building-a-spacecraft-with-perl-6/

Another option for simple objects is to use .perl to 'store' then EVAL to 'read' ... from https://docs.perl6.org/routine/perl

> Returns a Perlish representation of the object (i.e., can usually be
> re-evaluated with EVAL to regenerate the object).
like image 24
p6steve Avatar answered Nov 10 '22 02:11

p6steve