如何解决从perl文件中的文本中提取并存储键值对中的值
我有一个文本文件,其中包含如下信息:
name=A
class=B
RollNo=C
我想在perl脚本中提取值
key(name) = value(A)
key(class) = value(B)
key(RollNo) = value(C)
键应作为具有值的变量导出。每当我们键入
print $name
输出应为'A'
我尝试过:
open my $fh,'<',$file_name
or die "Could not open sample.txt: $!";
my @lines = <$fh>;
my %hash;
while (<@lines>) {
chomp;
my ($key,$value) = split /=/;
next unless defined $value;
$hash{$key} = $value;
}
print %hash;
解决方法
您的代码看起来很不错,到目前为止您所做的大部分工作都有效。
最后,您运行print %hash
,但这并不能满足您的期望。这样会将哈希中的键和值“展开”到列表中并打印该列表。这样您就可以打印出所有键和值。
如果只需要一个值(例如,与“名称”键关联的值),则只需打印该值即可。
print $hash{name};
是您要找的吗?
,您可以尝试使用可用的配置模块之一。 cinebench似乎适合您的数据:
use strict;
use warnings;
use Data::Dumper;
use Config::Tiny;
my $Config = Config::Tiny->new;
$Config = Config::Tiny->read( 'a.txt' ); # your text file name goes here
print $Config->{_}{name}; # print the name value
print Dumper $Config; # print all the values in perl variable format
,
您可以将数据存储在哈希中,也可以从哈希中检索。
use strict;
use warnings;
use Data::Dumper;
my %hash = (
name => 'A',class => 'B',RollNo => 'C'
);
print Dumper(\%hash);
print $hash{'name'};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。