使用Perl从文本文件中提取和打印键-值对 [英] Extraction and printing of key-value pair from a text file using Perl

查看:254
本文介绍了使用Perl从文本文件中提取和打印键-值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件temp.txt,其中包含类似

I have a text file temp.txt which contains entries like,

cinterim=3534
cstart=517
cstop=622
ointerim=47
ostart=19
ostop=20

注意:键值对可以换行,也可以一次排成一行,并以空格隔开.

Note: key-value pairs may be arranged in new line or all at once in one line separated by space.

我正在尝试使用Perl将这些值打印并存储在DB中,以用于相应的键.但是我收到很多错误和警告.现在,我只是尝试打印这些值.

I am trying to print and store these values in DB for corresponding keys using Perl. But I am getting many errors and warnings. Right now I am just trying to print those values.

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);

有人可以提供帮助来完善我的程序吗?

Could somebody provide help to refine my program.

推荐答案

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;

此代码的作用:

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

<$fh> reads a line from our file, or in list context, all lines and returns them as an array.

map内部,我们使用regexp /= | \s+/x将行拆分为一个数组.这意味着:当您看到=或一系列空格字符时拆分.这只是原始代码的精简和美化形式.

Inside map we split our line into an array using the regexp /= | \s+/x. This means: split when you see a = or a sequence of whitespace characters. This is just a condensed and beautified form of your original code.

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

Then, we cast the list resulting from map to the hash type. We can do that because the item count of the list is even. (Input like key key=value or key=value=valuewill throw an error at this point).

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

After that, we print the hash out. In Perl, we can interpolate hash values inside strings directly and don't have to use printf and friends except for special formatting.

for循环遍历所有键(在$_特殊变量中返回),而$hash{$_}是对应的值.这也可能写成

The for loop iterates over all keys (returned in the $_ special variable), and $hash{$_} is the corresponding value. This could also have been written as

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

其中each遍历所有键值对.

这篇关于使用Perl从文本文件中提取和打印键-值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆