Store and read hash and array in files in Perl

前端 未结 4 738
眼角桃花
眼角桃花 2020-11-29 10:01

I\'m a noob.I need some basic knowledge about how data should be saved and read under perl. Say to save a hash and an array. What format (extension) of file should be used?

相关标签:
4条回答
  • 2020-11-29 10:19

    If you new I just suggest make to string from array/hash with join() and they write it with "print" and then read and use split() to make array/hash again. That would be more simple way like Perl teaching text book example.

    0 讨论(0)
  • 2020-11-29 10:23

    Perlmonks has two good discussions on serialization.

    • How to save and reload my hash
    • How can I visualize my complex data structure?
    0 讨论(0)
  • 2020-11-29 10:27

    This really depends upon how you'd like store your data in your file. I will try writing some basic perl code to enable you to read a file into an array and or write back a hash into a 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;
    }
    
    0 讨论(0)
  • 2020-11-29 10:31

    You're looking for data serialisation. Popular choices that are robust are Sereal, JSON::XS and YAML::XS. Lesser known formats are: ASN.1, Avro, BERT, BSON, CBOR, JSYNC, MessagePack, Protocol Buffers, Thrift.

    Other often mentioned choices are Storable and Data::Dumper (or similar)/eval, but I cannot recommend them because Storable's format is Perl version dependent, and eval is unsafe because it executes arbitrary code. As of 2012, the parsing counter-part Data::Undump has not progressed very far yet. I also cannot recommend using XML because it does not map Perl data types well, and there exists multiple competing/incompatible schemas how to translate between XML and data.


    Code examples (tested):

    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 up from here is object persistence.


    Also read: Serializers for Perl: when to use what

    0 讨论(0)
提交回复
热议问题