使用Perl从文本文件中提取和打印键值对

maa*_*r99 3 perl hash search extract

我有一个文本文件temp.txt,其中包含条目,

cinterim=3534
cstart=517
cstop=622
ointerim=47
ostart=19
ostop=20
Run Code Online (Sandbox Code Playgroud)

注意:键值对可以按新行排列,也可以一行排列在一行中.

我正在尝试使用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);
Run Code Online (Sandbox Code Playgroud)

有人可以提供帮助来完善我的计划.

cdt*_*its 9

use strict;
use warnings;

open my $fh, '<', '/root/temp.txt' or die "Unable to open file:$!\n";
my %hash = map { split /=|\s+/; } <$fh>;
close $fh;
print "$_ => $hash{$_}\n" for keys %hash;
Run Code Online (Sandbox Code Playgroud)

这段代码的作用:

<$fh> 从我们的文件或列表上下文中读取一行,所有行并将它们作为数组返回.

在里面map我们使用正则表达式将我们的行分成一个数组/= | \s+/x.这意味着:当您看到一个=或一系列空白字符时拆分.这只是原始代码的浓缩和美化形式.

然后,我们将结果列表map转换为hash类型.我们可以这样做,因为列表的项目数是偶数.(输入喜欢key key=valuekey=value=value将在此时抛出错误).

之后,我们打印出哈希.在Perl中,我们可以直接在字符串内插入哈希值printf,除了特殊格式之外,不必使用和朋友.

for对所有的键循环迭代(在返回的$_特殊变量),并且$hash{$_}是相应的值.这也可以写成

while (my ($key, $val) = each %hash) {
  print "$key => $val\n";
}
Run Code Online (Sandbox Code Playgroud)

其中,each在所有键值对迭代.


小智 5

试试这个

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;
Run Code Online (Sandbox Code Playgroud)