2011-10-10 87 views
-2

我试图重用我们在内部使用的库函数,但是由于我的输入中有新的变体,所以事情并不正确,并且出现错误。Perl哈希键的合法值

我意识到问题在于它现在试图将一个时髦的句子指定为哈希键,例如下面的键列表,并且正如您所期望的那样,它并不喜欢它。有没有一种方法可以在对它进行哈希处理之前对其进行编码,以防止Perl出现任何堵塞现象?

Document: Multiple Attribute Equals (#root3 #form input[type=hidden], #root3 #form input[type=radio]) 
Document: Attribute selector using UTF8 (#root3 span[lang=中文]) 
Document: Attribute Ends With (#root3 a[href $= 'org/']) 
Document: Attribute Contains (#root3 a[href *= 'google']) 
Document: Select options via [selected] (#root3 #select1 option[selected]) 
Document: Select options via [selected] (#root3 #select2 option[selected]) 
Document: Select options via [selected] (#root3 #select3 option[selected]) 
Document: Grouped Form Elements (#root3 input[name='foo[bar]']) 
Document: :not() Existing attribute (#root3 #form select:not([multiple])) 
Document: :not() Equals attribute (#root3 #form select:not([name=select1])) 
+9

任何字符串都是Perl中的合法哈希键,包括所发布内容的所有字符串和子字符串。此外,几乎任何标量值都可以转换为字符串并用作散列键,包括对列表,数组和大多数类实例的引用。所以不,我不一定会期望你使用哈希的函数不喜欢它。那么你试图避免的具体错误和噱头是什么?这些输入是什么给你带来麻烦? – mob

+3

@mob:恩说。无可否认,使用字符串化引用作为散列键通常不是非常有用,但有一个_can_可以做到。实际上,你的评论中的“几乎”是不需要的:如果要求将标量_any_标量转换为字符串,则perl _will_将其转换为字符串,即使它可能会在执行时发出咳嗽和劈啪声并发出警告。 (好吧,我想可以使一个超载的标量的字符串转换例程“死亡”,但这只是简单的愚蠢。) –

+0

也许你应该显示一些代码和错误。 – TLP

回答

7

任何字符串都是允许的。任何不是字符串的东西都会先被串起来。

1

另存为文件并运行它:

use strict; 
use warnings; 
use Data::Dumper; 
my %hash; 
open(my $fh, '<', $0) or die 'Could not open myself!'; 
$hash{ do { local $/ = <$fh>; } } = 1; 
print Dumper(\%hash), "\n"; 
2

正如其他人所指出的,没有什么限制,允许作为哈希键。如果您使用参考,它将变成一个字符串。

但是,有些时候你不需要引号和时间,当你确实需要你的散列键引号时。如果您有空格或非字母数字字符,则需要使用散列键引号。有趣的是,如果只使用数字字符,则可以使用句点。否则,您不能使用时间而不会放在引号键:

$hash{23.23.23} = "Legal Hash Key"; 
$hash{foo.bar} = "Invalid Hash Key"; 
$hash{"foo.bar"} = "Legal Hash Key because of quotes"; 

而且,就看你使用引用作为重点会发生什么:

#! /usr/bin/env perl 

use strict; 
use warnings; 
use feature qw(say); 
use Data::Dumper; 

my %hash; 
my $ref = [qw(this is an array reference)]; 
$hash{$ref} = "foobar"; #Using Array Reference as Key 

say "\nDUMP: " . Dumper \%hash; 

产地:

DUMP: $VAR1 = { 
     'ARRAY(0x7f8c80803ed0)' => 'foobar' 
    }; 

所以,数组引用是stringified,即corserced到一个字符串。

不幸的是,你没有发布任何代码,所以我们真的不能说你的错误是什么。也许你需要在散列键周围加上引号。或者,也许还有另一个问题。

0

空字符串“”是Perl哈希键的另一个合法值。

刚才我偶然发现它时,我对此提出了一个疑问,但它与这些答案中已经提到的规则完全一致:任何字符串都允许为散列键。

在我的情况下,它非常有用。