2013-03-01 118 views
-2

我正在用XML :: TWIG解析一个巨大的文本XML文件。我必须将数据转换为标准的CSV,以便稍后将其输入到SQL数据库中。 XML输入文件包含几个客户的数据。一些客户将拥有比其他客户更多的数据(更多标签)。所以我一直把所有的数据放入哈希中,以便我可以区分哈希中的标记。Perl - 哈希错误 - 作为符号错误的未定义值

我重置每个客户的散列。现在,任何客户可以有额外的标记,当我试图打印出的哈希对于未被定义的键,它会给出错误:

Can't use an undefined value as a symbol reference at xml.pl at line 129 

的示例代码

print $hash(aKeyWhichWasNotDefined); 

是无论如何打印出一个空字符串,如果哈希键不存在?

+1

你确定这是你写的吗? '$ hash {aKeyWhichWasNotDefined}'会是一个散列参考... – 2013-03-01 13:16:11

回答

3

正确的方式来获得一个哈希值是

print $hash{aKeyWhichWasNotDefined}; 

也就是说,使用{(大括号)不((括号内)。

如果您打印未初始化的值,您仍会收到警告。 Perl的5.10+可以使用定义,或运营商:

print $hash{'non-existent-key'} // ''; 

在早期的皮尔斯,做硬盘的方式:

print defined $hash{'non-existent-key'} ? $hash{'non-existent-key'} : ''; 
4

首先,正确的语法是:

$hash{aKeyWhichWasNotDefined}; 

可以使用定义,或运营商作为一个快速的解决方案:

print $hash{aKeyWhichWasNotDefined} // ''; 

existsdefined也让你检查一个哈希键。

if (exists $hash{key}) { print "key exists but the value could be undefined" } 
if (defined $hash{key}) { print "key exists and has a defined value" } 
+0

谢谢丹,它的工作原理。 :) – Muzammil 2013-03-01 13:17:52