Perl6 equivalent of Perl's 'store' or 'use Storable'
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
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).
I seriously think you should move away from Storable and over to JSON. If you're using Rakudo Star as your install it includes a number of different JSON modules as part of it's core install so you don't need to add anything extra.
JSON is compatible with a number of different languages (not just Perl) and is a defined standard (unlike Storable which is backward incompatible). And JSON file sizes are of a similar size (if not smaller).
About the only plus point of Storable over JSON is handling code references. But if you're just storing data I wouldn't advise using Storable.