Perl哈希键的合法值

Perl哈希键的合法值,perl,hash,Perl,Hash,我试图重用我们内部的一个库函数,但由于我的输入中出现了新的变体,所以无法正常工作,并抛出错误 我意识到问题是它现在正试图分配一个时髦的句子作为散列键,比如下面的键列表,正如你所料,它不喜欢它。有没有一种方法可以在散列之前对其进行编码,以防止Perl出现任何形式的阻塞 Document: Multiple Attribute Equals (#root3 #form input[type=hidden], #root3 #form input[type=radio]) Document: Attr

我试图重用我们内部的一个库函数,但由于我的输入中出现了新的变体,所以无法正常工作,并抛出错误

我意识到问题是它现在正试图分配一个时髦的句子作为散列键,比如下面的键列表,正如你所料,它不喜欢它。有没有一种方法可以在散列之前对其进行编码,以防止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]))

允许任何字符串。任何非字符串的内容都将首先进行字符串化。

将其保存为文件并运行:

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";
使用严格;
使用警告;
使用数据::转储程序;
我的%hash;

open(my$fh,正如其他人所说,哈希键的允许范围没有限制。如果使用引用,它将转换为字符串

但是,有时您不需要引号,有时您确实需要在散列键周围加引号。如果您有空格或非字母数字字符,则需要在散列键周围加引号。有趣的是,如果您只使用数字字符,则可以使用句点。否则,如果不在键周围加引号,则不能使用句点:

$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'
    };
因此,数组引用被字符串化,也就是说,被强制为字符串

不幸的是,您没有发布任何代码,因此我们无法确定您的错误是什么。可能您需要在哈希键周围添加引号。或者,可能还有另一个问题。

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

当我刚才偶然发现它时,我对此感到惊讶,但它完全符合这些答案中已经说明的规则:任何字符串都可以是散列键


在我的例子中,它非常有用。

任何字符串在Perl中都是合法的哈希键,包括您发布的内容的所有字符串和子字符串。此外,几乎任何标量值都可以转换为字符串并用作哈希键,包括对列表、数组和大多数类实例的引用。因此,不,我不一定希望您的函数使用哈希不喜欢。那么,你试图避免的具体错误和噱头是什么?这些输入给你带来了什么麻烦?@mob:说得好。诚然,使用字符串化引用作为哈希键通常不是很有用,但你可以做到。事实上,“几乎”在您的注释中,这是不必要的:如果要求将标量、任何标量转换为字符串,perl都会将其转换为字符串,即使它在转换过程中可能会咳嗽、飞溅并发出警告。(好吧,我想可以制作一个重载标量,其字符串转换例程
死亡
s,但这太愚蠢了。)也许你应该显示一些代码和错误。mod-1:没有代码。请发布一些代码。这会让你更容易弄清楚到底发生了什么。然后,为了不那么假惺惺,有必要找回你的参考资料。