在perl中使用外部文本文件中的哈希数据结构

在perl中使用外部文本文件中的哈希数据结构,perl,data-structures,perl-module,Perl,Data Structures,Perl Module,我是perl的初学者。下面的脚本解析散列中存储的值,如果字符串不存在,则抛出一个错误 #!usr/bin/perl use feature qw/say/; $hash = { 'testing' => { 'link' => "http://www.espn.com", 'bandwidth' => "100", 'r' => "2", }, }; die "'testing' not found!" unless($hash-&g

我是perl的初学者。下面的脚本解析散列中存储的值,如果字符串不存在,则抛出一个错误

#!usr/bin/perl

use feature qw/say/;

$hash = {
  'testing' => {
    'link' => "http://www.espn.com",
    'bandwidth' => "100",
    'r' => "2",
  },
};

die "'testing' not found!" unless($hash->{'testing'});

say $hash->{'testing'}->{'link'} // (die "'link' not found!");
say $hash->{'testing'}->{'bandwidth'} // (die "'bandwidth not found!");
上述程序的输出是

http://www.espn.com
100
现在,我希望散列值存储在一个txt文件中,比如hash.txt,而不是在脚本中指定该值。如何在脚本中调用该文本文件

下面的值是在hash.txt文件中指定的。我不确定如何在脚本中调用此文件。有什么建议吗

'testing' => {
        'link' => "http://www.espn.com",
        'bandwidth' => "100",
        'r' => "2",
      },

尝试类似的方法,假设您希望散列中的值存储在名为
in.txt
的文件中,如下所示:

http://www.espn.com 100 2
www.example.com 20  1
www.no_bandwith.com     1
(请注意,第三个条目缺少带宽值)


核心可存储模块可用于轻松序列化数据结构:

use Storable;
store \%table, 'file';
$hashref = retrieve('file');
Storable的许多函数在出现故障时抛出异常(即它们
die
),而不是返回
undef
,因此,如果需要恢复,我建议使用
Try::Tiny
模块——这比尝试手动正确保存$@要容易得多

也可以使用
Data::Dumper
编写明文文件,然后将其全部读入并
eval
以重新创建数据结构。稍微复杂一点,但是生成的存储文件比
可存储的
创建的文件更容易让人阅读。要将其读回,您可以自己实现:

use autodie; # For the convenience of this example;
             # makes all open()s, close()s, etc die
             # without needing to type `or die "$!\n";' repeatedly

my $serialized_hash = do {
    open my $fh, '<', 'hash.txt';
    local $/; # Undefine $/ for this scope...
    <$fh>;    # so <> slurps up the entire file
};
然后
eval
it

my %hash;
eval $data;
另外,如果要检查散列中是否存在键而不是是否定义了其值,请使用
exists
函数,该函数与
delete
一起工作

资料来源:

perldoc可存储


perldoc-f存在

您需要学习基本原理和“在
核心
中”执行类似操作的技术,并充分掌握Perl语言(对于在您的情况下存储/检索数据结构,
可存储
是一个不错的选择),因此,请坚持使用本文中其他一些经过验证的真实回答。您最终会想了解使用JSON、YAML等的各种模块以及其他序列化数据的方法

但是,为了激发您的兴趣,这里有一个示例,说明您可以使用一个新的
perl
和一些CPAN模块做什么:

#!/usr/bin/env perl

use 5.10.0;
use DDP;
use IO::All;

my $testing_hash < io './testing.hash' ;
my $hash = { eval $testing_hash } ;

p $hash ;

say $hash->{'testing'}{'link'} // (die "'link' not found!");
中的CPAN模块在此处使用:

  • 用于调试打印
  • 对于可能太简单的IO

如果数据以以下格式存储,脚本是否有效。”测试“=>{”链接“=>”,“带宽”=>“100”,“r”=>“2”,},当我编译脚本时,我得到以下错误。在中使用未初始化的值$in。未打开的文件handleopen my$in上的readline(),顺便说一句,这假设您可以查看
testing.hash中的内容,并且可以信任您看到的内容:-)
use File::Slurp;
my $serialized_hash = read_file('hash.txt');
my %hash;
eval $data;
#!/usr/bin/env perl

use 5.10.0;
use DDP;
use IO::All;

my $testing_hash < io './testing.hash' ;
my $hash = { eval $testing_hash } ;

p $hash ;

say $hash->{'testing'}{'link'} // (die "'link' not found!");
\ {
    testing   {
        bandwidth   100,
        link        "http://www.espn.com",
        r           2
    }
}
http://www.espn.com