我有一个字符串
$str = "xxxxxx Code File(s) Name:Some_thing.c CodeFile(s) Version:27 Design Document:some_other_design.doc Module Design Document Version:43 somexxxxxxxxxx Compiler Version:9.5 Doc Type:Word xxxxxx";
其中xxxxx代表任何字符。但我只对提取每个属性的值感兴趣。
即我要保存
$fileName = Some_thing.c;
$fileVersion = 27;
$designDocName = some_other_design.doc;
$designDocVersion = 43;
$compilerVersion = 9.5;
现在我觉得我有一个混乱的解决方案。只是想知道是否有更清洁的方法来做到这一点。如果我有多个版本的多个文件,这也可能会失败。
首先我删除所有空格,然后我将字符串拆分为2直到我得到所有值
$str =~ s/\s*//g;
($temp,$temp2) = split(/CodeFile\(s\)Name:/,$str,2);
($fileName,$temp) = split(/CodeFile\(s\)Version:/,$temp2,2);
($fileVersion,$temp2) = split(/DesignDocument:/,$temp,2);
($designDocName,$temp) = split(/DesignDocumentVersion:/,$temp2,2);
($designDocVersion,$temp2) = split(/some/,$temp,2);
($testedCompilerVersion,$temp) = split(/CompilerVersion:/,$temp2,2);
($testedCompilerVersion,$temp2) = split(/DocType:/,$temp,2);
请引导我找到链接或有效的解决方案。 提前谢谢。
PS:请同时查看问题下方的评论。
答案 0 :(得分:2)
也许以下内容会有所帮助:
use strict;
use warnings;
use Data::Dumper;
my $str = "xxxxxx Code File(s) Name:Some_thing.c CodeFile(s) Version:27 Design Document:some_other_design.doc Module Design Document Version:43 somexxxxxxxxxx Compiler Version:9.5 Doc Type:Word xxxxxx";
my @labels = qw/fileName fileVersion designDocName designDocVersion compilerVersion docType/;
my ($i, %items) = 0;
$items{$labels[$i++]} = $1 while $str =~ /.+?:(\S+)\s+?/g;
print Dumper \%items
输出:
$VAR1 = {
'designDocName' => 'some_other_design.doc',
'fileName' => 'Some_thing.c',
'docType' => 'Word',
'designDocVersion' => '43',
'fileVersion' => '27',
'compilerVersion' => '9.5'
};
答案 1 :(得分:0)
虽然我会使用 @Kenosis 解决方案,但我仍然希望向您展示您的脚本可以简化。
#!/usr/bin/perl
use v5.14;
use warnings;
my $str = "xxxxxx Code File(s) Name:Some_thing.c CodeFile(s) Version:27 Design Document:some_other_design.doc Module Design Document Version:43 somexxxxxxxxxx Compiler Version:9.5 Doc Type:Word xxxxxx";
my ($fileName,
$fileVersion,
$designDocName,
$designDocVersion,
$compilerVersion) = $str =~ /:(\S+)/g;
say "$fileName, $fileVersion, $designDocName, $designDocVersion, $compilerVersion";
#Some_thing.c, 27, some_other_design.doc, 43, 9.5
答案 2 :(得分:0)
my ($fileName, $fileVersion, $designDocName, $designDocVersion, $compilerVersion) =
$str =~ /Code File\(s\) Name:(.*) CodeFile\(s\) Version:(.*) Design Document:(.*) Module Design Document Version:(.*) somexxxxxxxxxx Compiler Version:(.*) Doc Type:(.*) xxxxxx/;