gpt4 book ai didi

perl - Perl散列是否应始终包含值?

转载 作者:行者123 更新时间:2023-12-03 22:53:01 25 4
gpt4 key购买 nike

我有一个较早的问题,该问题来自著名的Perl专家,Perl作者和Perl培训师brian d foy的following response:

[If] you're looking for a fixed sequence of characters at the end of each filename. You want to know if that fixed sequence is in a list of sequences that interest you. Store all the extensions in a hash and look in that hash:
    my( $extension ) = $filename =~ m/\.([^.]+)$/;    if( exists $hash{$extension} ) { ... }
You don't need to build up a regular expression, and you don't need to go through several possible regex alternations to check every extension you have to examine.


感谢您的建议布赖恩。

我现在想知道的是,在上述情况下的最佳实践是什么。应该只定义键,而这正是我要实现上述要求的全部,还是应该总是定义一个值?

最佳答案

通常最好为每个键设置一个定义的值。惯用值(当您不关心该值时)为1。

my %hash = map { $_ => 1 } @array;

这样可以使使用哈希的代码更加简单,因为您可以将 $hash{key}用作 bool 值。如果该值无法定义,则需要使用更详细的 exists $hash{key}

就是说,在某些情况下需要 undef的值。例如:假设您正在解析C头文件以提取预处理器符号。将它们存储在名称=>值对的哈希中是合乎逻辑的。
#define FOO 1
#define BAR

在Perl中,这将映射到:
my %symbols = ( FOO => 1, BAR => undef);

在C语言中, #define定义符号而不是值-C语言中的“defined”映射为Perl语言中的“exists”。

关于perl - Perl散列是否应始终包含值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/917494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com