Using a hash data structure from an external text file with perl -
this question has reply here:
declaring hash table in 1 file , using in in perl 4 answersi'm beginner in perl.the below script parses value stored in hash , throws error if string not present.
#!usr/bin/perl utilize feature qw/say/; $hash = { 'testing' => { 'link' => "http://www.espn.com", 'bandwidth' => "100", 'r' => "2", }, }; die "'testing' not found!" unless($hash->{'testing'}); $hash->{'testing'}->{'link'} // (die "'link' not found!"); $hash->{'testing'}->{'bandwidth'} // (die "'bandwidth not found!"); out set of above programme
http://www.espn.com 100 now instead of specifying value in script want hash value stored in txt file hash.txt . how phone call text file in script.
the below value specified in file hash.txt .i'm not sure how phone call file in script. suggestions?
'testing' => { 'link' => "http://www.espn.com", 'bandwidth' => "100", 'r' => "2", },
the core module storable can used serialize info structures painlessly:
use storable; store \%table, 'file'; $hashref = retrieve('file'); many of storable's functions throw exceptions (i.e. die) rather homecoming undef on failure, recommend using try::tiny module if recovery necessary--it's lot easier trying tackle headache of preserving $@ manually.
it's possible write write plaintext file using data::dumper, read in , eval recreate info structure. bit more complicated, resulting storage file much more human readable storable creates. read in, can either implement yourself:
use autodie; # convenience of example; # makes open()s, close()s, etc die # without needing type `or die "$!\n";' repeatedly $serialized_hash = { open $fh, '<', 'hash.txt'; local $/; # undefine $/ scope... <$fh>; # <> slurps entire file }; or utilize file::slurp (also in core, , quite efficient)
use file::slurp; $serialized_hash = read_file('hash.txt'); then eval it
my %hash; eval $data; also if you're checking whether key exists in hash rather if value defined, utilize exists function, works in tandem delete.
sources:
perldoc storable
perldoc -f exists
perl data-structures perl-module
No comments:
Post a Comment