所以,我有这个文件,其中包含不同文件的不同路径,以及文件的类型随行中的更改次数而变化。像这样的东西
abc123:
Files Changed: lines: new deleted unchanged
some/path/to/file.c 15 0 4234
some/other/file.h 1 0 223
some/other/path/to/file2 3 1 3
Files Created: lines: new deleted unchanged
some/path/to/file.c 3 1 3
Files Changed: lines: new deleted unchanged
some/other/path/to/file 2 2 234
我需要找到一种简单的解析方法。我真的不在乎线条的变化(新的,删除的,不变的)。我想要的是拥有一个JSON。像这样:
{
"abc123":{
"Files Changed:": [
"some/path/to/file.c",
"some/other/file.h",
"some/other/path/to/file",
"some/other/path/to/file2"
],
"Files Created:":[
"some/path/to/file.c"
]
}
}
更难的部分是尝试解析文本文件我想要的东西可以使用文件提供给你的任何东西。我肯定知道可能有用的是任何有'/'然后是文件字符串但我不知道如何告诉它是'文件已更改'或'文件已创建'。此外,该文件可能具有“文件已删除”,“文件链接”及其相应的文件路径。任何帮助如何实现这一点将是值得欣赏的。
答案 0 :(得分:3)
只要行开头的空格是一致的,这很容易实现。您需要逐行阅读并记住您在哪个级别上看到的内容。
在下面的代码中,我假设每个级别有两个缩进空格。由于这看起来像某种版本控制摘要,我正在调用
$commit
,$operation
。use strict;
use warnings;
use JSON 'to_json';
my $commit; # abc123
my $operation; # Files Changed, Files Created
my $data; # this is the target
while (my $line = <DATA>) {
if ($line =~ /^(\S+):/) {
# line contains a commit
$commit = $1;
next;
}
if ($line =~ /^\s\s([^:]+):/) {
# line contains an operation
$operation = $1;
next;
}
if ($line =~ /^\s\s\s\s(\S+)/) {
# this is a filename
push @{ $data->{$commit}->{$operation} }, $1;
}
}
print to_json $data;
__DATA__
abc123:
Files Changed: lines: new deleted unchanged
some/path/to/file.c 15 0 4234
some/other/file.h 1 0 223
some/other/path/to/file2 3 1 3
Files Created: lines: new deleted unchanged
some/path/to/file.c 3 1 3
Files Changed: lines: new deleted unchanged
some/other/path/to/file 2 2 234
这会产生以下输出。
{"abc123":{"Files Changed":["some/path/to/file.c","some/other/file.h","some/other/path/to/file2","some/other/path/to/file"],"Files Created":["some/path/to/file.c"]}}