declaring a hash table in one file and using it in another in Perl

后端 未结 4 1180
梦如初夏
梦如初夏 2020-12-11 10:01

I need to create a hash table in one file and use in in another. The reason for it is that that the table is my \"database\" and will be changed, and I want it to seat with

相关标签:
4条回答
  • 2020-12-11 10:30

    Define your hashtable in a global or package variable. Then use the do command to load the definition into another script:

     datafiles/database.def
     ---------------------------
     package ProjectData;
     our %DATA = ('abc' => 'def', 'ghi' => 'jkl', ...);
    
    
     scripts/myscript.pl
     ------------------------
     use strict;
     do 'datafiles/database.def';
     ... do something with %ProjectData::DATA ...
    
    0 讨论(0)
  • 2020-12-11 10:30

    This is likely not be the best solution, but you could just use Storable or Data::Dumper, both of which are in the core since forever (5.7.3 and 5.5, respectively).

    Alternatively, you could put them in another module and use/require that, ala

    package MyImportantHash;
    

    use Exporter;

    our @EXPORT = qw( %important_hash );
    
    our %important_hash = (
                  some_key  => 'some_value',
             );
    
    1;
    

    And in your main package,

    use MyImportantHash;
    say "$_ => $important_hash{$_}" for sort keys %important_hash;
    

    Of course, this all assumes that you don't want changes in the hash while in-memory to automatically show up in the file. If you do, look no further than davorg's answer.

    0 讨论(0)
  • 2020-12-11 10:38

    There are too many ways to do it!

    A simple one is to write your data to a file as CSV and load it using Text::CSV or Text::CSV_XS.

    update:

    You can also use the do builtin to read and execute a perl file from another script. I.e.:

    do "config.pl";
    

    Or use a configuration file format that allows for complex data structures (XML, JSON, yaml, .ini, etc.).

    0 讨论(0)
  • 2020-12-11 10:46

    Perhaps you're looking for a tied hash.

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