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
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:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With