我想提取一个文件,其中包含一个人的数据信息,如姓名,地址,电话..。该文件可以如下所示:
Name:John
FirstName:Smith
Address:Main Street
Phone:32674632
Name:Alice
FirstName:Meyers
Address:Forth Av.
Phone:273267462但有时地址写在两行:
Name:John
FirstName:Smith
Address:Main Street
Phone:32674632
Name:Alice
FirstName:Meyers
Address:Forth Av.
street 54
Phone:273267462我写了这个:
while (<INPUT>) {
chomp;
if (/^Name/) {
($match) = /Name:(.*)/;
$string = $string.$match." ";
next;
}
if (/^FirstName/) {
($match) = /FirstName:(.*)/;
$string = $string.$match." ";
next;
}
if (/^Address/) {
($match) = /Address:(.*)/;
$string = $string.$match." ";
next;
}
if (/Address:(.*)$Phone/) {
($match) = /Address:(.*)$phone/;
$string = $string.$match." ";
next;
}
if (/^Phone/) {
($match) = /Phone:(.*)/;
$string = $string.$match." ";
print OUTPUT "$string\n";
$string = "";
next;
}
}有人能帮我找到解决这些问题的方法吗?
发布于 2014-07-22 12:00:47
#!/usr/bin/perl -w
use warnings;
use strict;
use Data::Dumper;
my $key = '';
my %person = ();
while (<>) { # for each line
chomp;
if (/^(.+?):(.*)/) { # Do we have a key followed by a colon?
$key = $1; # the key is the part before the colon
$person{$key} = $2; # The value is the part after the colon
if ($key eq 'Phone') { # A line with a 'Phone' key is the last one for a person
print Dumper(\%person); # Dump our person
$key = '';
%person = (); # Start a new person
}
} else {
$person{$key} .= " $_"; # No key means just append this line to the value for the previous key
}
}发布于 2014-07-22 10:47:44
尝尝这个
if (/^Address/) {
($match) = /Address:(.*)$Phone/;
$string = $string.$match." ";
next;
} 如果您的文件包含相同的格式,即在“地址”之后,下一个记录是“电话”,则编写表达式以搜索地址和电话之间的完整字符串。/^Address:.*$Phone/
然后像这样搜索/^Address.* [\s.*:]$/
以地址开头,以空格结尾任何字符:。一定要起作用。
发布于 2014-07-22 11:06:21
@array=split /\nName/,<INPUT>;
while my $vals (@array) {
chomp($vals);
my @spls = ($1,$2,$3,$4) if($_=~/:(.*?)FirstName:(.*?)Address:(.*?)Phone:(.*)/);
chomp(@spls);
my $string = join(" ",@spls);
print OUTPUT "$string\n";
}https://stackoverflow.com/questions/24884682
复制相似问题