问题
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
回答1:
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
回答2:
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).
回答3:
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.
来源:https://stackoverflow.com/questions/54465122/perl6-equivalent-of-perls-store-or-use-storable