Perl自动执行哈希填充和键名

问题描述 投票:1回答:1

我有许多错误字符串。我正在将它们与已有的模式匹配。如果它们完全相同,我希望它们属于完全相同的错误失败。如果它们与模式匹配,但与哈希中的先前字符串有一些区别,我想给它提供相同的错误名称,但附加一个不同的数字。

这是示例输入文件:

there are 5 syntax issues with semicolon
there are 11 syntax issues with semicolon
the file contains 5 formatting issues
there are 1 syntax issues with semicolon
check script for formatting issues
2 syntax issues have been found
the file contains 1 formatting issues
6 syntax issues have been found
use warnings;
use strict;

my %errors;
my $file = "listoferrormessages.txt"

open my $fh,'<',$file or die "Could not open $file: $!";

while(my $line = <$fh>){

if( $line =~ /syntax/){

    if ($line =~ /there are \d syntax issues with semicolon/){
       #if line matching format exists in hash values, continue
       #if not, create a hash key called syntax_# where # increments one from the last key with the error name. 
        $errors{errorname} = $line;
}

    elsif ($line =~ /\d syntax issues have been found/){
       #same as above
       $errors(errorname} = $line;
}

elsif ($line =~ /format/){
#same as above
}

}
close $fh;

我希望我的哈希看起来像:

$VAR1 = {
          'syntax_1' => 
                     'there are 5 syntax issues with semicolon',
          'syntax_2' => 
                     '2 syntax issues have been found',
          'format_1' => 
                     'the file contains 5 formatting issues',
          'format_2' => 
                     'check script for formatting issues'
        };

关于此的任何指导都将非常有帮助。我还想补充很多,但是我对如何开始这样做感到非常困惑。这甚至有可能做到吗?

perl
1个回答
0
投票

这是所要回答的问题,但仍有一些问题。

[辅助数据结构(%seen_error_type)有助于避免每次都进行搜索。

use warnings;
use strict;
use feature qw(say);

use Data::Dump qw(dd);  # to show complex data structures

my $file = shift // die "Usage: $0 file;  #/
open my $fh, '<', $file  or die "Can't open $file: $!";

my (%error, %seen_error_type, $cnt_syntax, $cnt_format);

LINE:
while (my $line = <$fh>) { 
    chomp $line;

    my $error_type = $line =~ s/[0-9]+/N/r;  # extract error type

    next LINE if exists $seen_error_type{$error_type};
    $seen_error_type{$error_type} = 1;

    if ($line =~ /syntax/) {
        ++$cnt_syntax;
        $error{ "syntax_$cnt_syntax" } = $line;
    }
    elsif ($line =~ /format/) {
        ++$cnt_format;
        $error{ "format_$cnt_format" } = $line;
    }   
    else { }  # handle unknown / unexpected error types
}       

dd \%error;

最关键的是要阐明预期的“错误类型”的规则。

我根据显示的示例通过用N替换数字来创建“类型”。如果这就是全部,那就这样吧。但是,如果对于预期将要编码的错误有更复杂的标准。

除非我们对如何从行中提取模式有一些规则,否则在错误类型的簿记哈希中简单地添加意外模式是没有意义的;否则,每个可能的文本行都可能成为其自身的键,这将破坏整个练习的目的。

请澄清可能的错误类型和相关选项,我将进行相应的更新。

[另一条注释,已经在注释中提出:我不明白为什么要为每行添加一个键,而不是将每个“语法”类型错误行添加到作为键syntax值的arrayref中,与format等相同。知道原因可能有助于我建议更合适的代码。


使用上面显示的输入文件打印

{  format_1 =>“该文件包含5个格式问题”,  format_2 =>“检查脚本是否存在格式问题”,  语法_1 =>“分号有5个语法问题”,  语法_2 =>“已发现2个语法问题”,}
© www.soinside.com 2019 - 2024. All rights reserved.