Store and read hash and array in files in Perl

I noob.I need some basic knowledge on how data should be saved and read in perl. Say save a hash and an array. What file format (extension) should be used? text? For now, I can save all things as a print FILE %hash and read them as a print <FILE> . What if I need hash functions and array input from a file. How to return them to hash and array?

+8
arrays file perl save hash
source share
4 answers

You are looking for serialization . Popular options that are reliable are Sereal , JSON :: XS and YAML :: XS , Little-known formats: ASN.1 , Avro , BERT , BSON , CBOR , JSYNC , MessagePack , Protocol buffers , Thrift .

Other commonly mentioned options are: Storable and Data :: Dumper (or similar) / eval , but I cannot recommend them because the saved format depends on the version of Perl, and eval unsafe because it runs arbitrary code. As of 2012, the analysis of the Data :: Undump partition did not go very far. I also cannot recommend using XML because it does not display Perl data types well and there are several competing / incompatible schemes for translating between XML and data.


Code examples (testing):

 use JSON::XS qw(encode_json decode_json); use File::Slurp qw(read_file write_file); my %hash; { my $json = encode_json \%hash; write_file('dump.json', { binmode => ':raw' }, $json); } { my $json = read_file('dump.json', { binmode => ':raw' }); %hash = %{ decode_json $json }; } 

 use YAML::XS qw(Load Dump); use File::Slurp qw(read_file write_file); my %hash; { my $yaml = Dump \%hash; write_file('dump.yml', { binmode => ':raw' }, $yaml); } { my $yaml = read_file('dump.yml', { binmode => ':raw' }); %hash = %{ Load $yaml }; } 

The next step from here is to save the objects .


Also read: Serializers for Perl: when to use what

+19
source share

Perlmonks has two good discussions about serialization.

+3
source share

It depends on how you want to store your data in your file. I will try to write the basic perl code so that you can read the file in an array and write the hash to the file.

 #Load a file into a hash. #My Text file has the following format. #field1=value1 #field2=value2 #<FILE1> is an opens a sample txt file in read-only mode. my %hash; while (<FILE1>) { chomp; my ($key, $val) = split /=/; $hash{$key} .= exists $hash{$key} ? ",$val" : $val; } 
+1
source share

If you're new, I just suggest make for a string from an array / hash with join (), and they write it with "print" and then read and use split () to create the array / hash again. This would be a simpler way, for example, in the example with the Perl tutorial.

0
source share

All Articles