Perl:调试未初始化的s ///?

问题描述:

我的程序遇到了一些问题。收到错误:Perl:调试未初始化的s ///?

Use of uninitialized value in substitution (s///)

我意识到这之前已经问过,但没有帮助我。我知道$1可能是单元化的,但我想知道你们是否可以帮我弄清楚为什么?

下面的代码的问题部分:

$one_match_ref->{'sentence'} = $1 if ($line =~ /^Parsing \[sent. \d+ len. \d+\]: \[(.+)\]/); 
$one_match_ref->{'sentence'} =~ s/,//g; 

编辑:我已经宣布了$one_match_ref->{'sentence'}像这样:

my $sentence; 
$one_match_ref = { 
     chapternumber => $chapternumber_value, 
     sentencenumber => $sentencenumber_value, 
     sentence => $sentence, ##Get from parsed text: remove commas 
     grammar_relation => $grammar_relation_value, ##Get from parsed text: split? 
     arg1 => $argument1, ##Get from parsed text: first_dependencyword 
     arg2 => $argument2 ##Get from parsed text: second_dependencyword 
    }; 

但所有这些变量的任何东西都分配给他们。

我尝试:

A.如果我把:if(defined (one_match_ref->{'sentence'}))后的S ///,它的工作原理。但是这很麻烦,而且似乎避免了问题而不是修复它。

我最后一次使用该修复程序,这是因为我的循环出现了“错误的”错误,我不认为这是这种情况。

B.如果我宣布:my $sentence = '';它打印,但大量的空行之间。我如何消除这些?

编辑:为了兴趣和效率的目的:使用split得到我想要的更好吗?

在此先感谢您的任何帮助或建议。让我知道如果你需要一个文件格式的例子。

+0

Perl是所有关于细节。那些“打印空白行”并没有真正提供任何信息。我们需要查看代码,输入和期望的输出。错误**和**行号也很好。 任何人都无法说出分割是否会更好,没有看到输入或知道你现在在使用什么。 除非我们看到您的打印声明,否则我们无法说出它为什么会打印大量空白行。 – TLP 2011-06-10 07:28:28

+0

我试着实现答案来自:http://*.com/questions/6298895/perl-beginner-which-data-structure-should-i-use 谢谢你让我知道,我已经添加了编辑部分(包括我目前所拥有的资源) – Jon 2011-06-10 14:21:29

+0

从未见过数据提取类型问题因为之前“太窄”而关闭。没有两个这样的问题是完全一样的。当我回到家时,我会看看这个,看看我能不能添加一些东西。 – TLP 2011-06-10 16:46:30

您的代码归结为

my $sentence; 
$one_match_ref = { sentence => $sentence }; 
() if ($line =~ /^Parsing \[sent. \d+ len. \d+\]: \[(.+)\]/); 
$one_match_ref->{'sentence'} =~ s/,//g; 

分配undef$one_match_ref->{'sentence'},然后尝试从中删除逗号。这没有任何意义,因此是警告。

也许你想

my $sentence; 
$one_match_ref = { sentence => $sentence }; 
if ($line =~ /^Parsing \[sent. \d+ len. \d+\]: \[(.+)\]/) { 
    $one_match_ref->{'sentence'} = $1; 
    $one_match_ref->{'sentence'} =~ s/,//g; 
} 
+0

令人惊叹!谢谢一堆。完美打破它。我以为我尝试过,但... – Jon 2011-06-10 07:28:11

我不确定这是$1这是未初始化在这里,而是$one_match_ref->{'sentence'}

当且仅当该行与正则表达式匹配时才设置该值。否则,它根本没有被触动。

我的推理是它在替代而不是分配中抱怨。你可以可能通过简单地将$one_match_ref->{'sentence'}设置为这两行之前的已知值(例如空字符串)来修复它。

但这取决于你实际使用这些值。

+0

我相信我确实将它设置为“”的已知值,但如前所述,它会打印许多空行。感谢您帮助进一步确定问题! – Jon 2011-06-10 04:02:01