0

我有一个字符串

 $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:还请检查问题下方的评论。

4

3 回答 3

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'
        };
于 2013-11-07T17:13:21.660 回答
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
于 2013-11-07T17:40:11.910 回答
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/;
于 2013-11-07T18:04:13.627 回答