使用Perl从文本文件中提取和打印键值对
我有一个文本文件temp.txt,其中包含如下条目:使用Perl从文本文件中提取和打印键值对,perl,search,hash,extract,Perl,Search,Hash,Extract,我有一个文本文件temp.txt,其中包含如下条目: cinterim=3534 cstart=517 cstop=622 ointerim=47 ostart=19 ostop=20 注:键值对可以排列在新行中,也可以一次全部排列在一行中,以空格分隔 我正在尝试使用Perl打印这些值并将其存储在DB中,以用于相应的键。但是我收到了很多错误和警告。现在我只是想打印这些值 use strict; use warnings; open(FILE,"/root/temp.txt") or die
cinterim=3534
cstart=517
cstop=622
ointerim=47
ostart=19
ostop=20
注:键值对可以排列在新行中,也可以一次全部排列在一行中,以空格分隔
我正在尝试使用Perl打印这些值并将其存储在DB中,以用于相应的键。但是我收到了很多错误和警告。现在我只是想打印这些值
use strict;
use warnings;
open(FILE,"/root/temp.txt") or die "Unable to open file:$!\n";
while (my $line = <FILE>) {
# optional whitespace, KEY, optional whitespace, required ':',
# optional whitespace, VALUE, required whitespace, required '.'
$line =~ m/^\s*(\S+)\s*:\s*(.*)\s+\./;
my @pairs = split(/\s+/,$line);
my %hash = map { split(/=/, $_, 2) } @pairs;
printf "%s,%s,%s\n", $hash{cinterim}, $hash{cstart}, $hash{cstop};
}
close(FILE);
使用严格;
使用警告;
打开(文件“/root/temp.txt”)或死“无法打开文件:$!\n”;
while(我的$line=){
#可选空白,键,可选空白,必需“:”,
#可选空白、值、所需空白、所需“.”
$line=~m/^\s*(\s+)\s*:\s*(.*)\s+\./;
my@pairs=split(/\s+/,$line);
我的%hash=map{split(/=/,$2)}@pairs;
printf“%s,%s,%s\n”、$hash{cinterim}、$hash{cstart}、$hash{cstop};
}
关闭(文件);
有人能帮我改进一下程序吗。试试这个
use warnings;
my %data = ();
open FILE, '<', 'file1.txt' or die $!;
while(<FILE>)
{
chomp;
$data{$1} = $2 while /\s*(\S+)=(\S+)/g;
}
close FILE;
print $_, '-', $data{$_}, $/ for keys %data;
使用警告;
我的%data=();
打开文件,'
其中,每个
迭代所有键值对。最简单的方法是将整个文件读入内存,并使用正则表达式将键值对分配给哈希
这个节目展示了这项技术
use strict;
use warnings;
my %data = do {
open my $fh, '<', '/root/temp.txt' or die $!;
local $/;
<$fh> =~ /(\w+)\s*=\s*(\w+)/g;
};
use Data::Dump;
dd \%data;
您将收到哪些错误和警告。请在此处显示它们。您的脚本不适合您的数据集--脚本正在“:”以“.”结尾”拆分数据行,但您的数据对以“=”分隔,而不是以“.”结尾。您可以添加一个解释吗?@cdtits:非常感谢,这很有帮助。
while (my ($key, $val) = each %hash) {
print "$key => $val\n";
}
use strict;
use warnings;
my %data = do {
open my $fh, '<', '/root/temp.txt' or die $!;
local $/;
<$fh> =~ /(\w+)\s*=\s*(\w+)/g;
};
use Data::Dump;
dd \%data;
{
cinterim => 3534,
cstart => 517,
cstop => 622,
ointerim => 47,
ostart => 19,
ostop => 20,
}