8

我正在编写一个可能被用户修改的脚本。目前我将配置设置存储在脚本中。它以散列哈希的形式存在。

我想防止人们在哈希键中意外使用小写字符,因为这会破坏我的脚本。

检查哈希键很简单,只需对任何带有小写字符的键发出警告,但我宁愿自动修复区分大小写的问题。

换句话说,我想将顶级哈希中的所有哈希键都转换为大写。

4

3 回答 3

15

安迪的答案是一个很好的答案,除了他uc是每一个关键,uc如果它不匹配,然后再s它。

uc是一次:

%hash = map { uc $_ => $hash{$_} } keys %hash;

但是,由于您谈到了用户存储密钥,因此平局是一种更可靠的方式,即使速度较慢。

package UCaseHash;
require Tie::Hash;

our @ISA = qw<Tie::StdHash>;

sub FETCH { 
    my ( $self, $key ) = @_;
    return $self->{ uc $key };
}

sub STORE { 
    my ( $self, $key, $value ) = @_;
    $self->{ uc $key } = $value;
}

1;

然后主要是:

tie my %hash, 'UCaseHash'; 

那是一个节目。“tie魔法”将它封装起来,让用户不会在不知不觉中乱用它。

当然,只要你使用“类”,你可以传入配置文件名并从那里初始化它:

package UCaseHash;
use Tie::Hash;
use Carp qw<croak>;

...

sub TIEHASH { 
    my ( $class_name, $config_file_path ) = @_;
    my $self = $class_name->SUPER::TIEHASH;
    open my $fh, '<', $config_file_path 
        or croak "Could not open config file $config_file_path!"
        ;
    my %phash = _process_config_lines( <$fh> );
    close $fh;
    $self->STORE( $_, $phash{$_} ) foreach keys %phash;
    return $self;
}

你必须这样称呼它:

tie my %hash, 'UCaseHash', CONFIG_FILE_PATH;

...假设一些常数CONFIG_FILE_PATH

于 2008-11-21T21:49:51.113 回答
13

遍历散列并用大写等效项替换任何小写键,并删除旧键。大致:

for my $key ( grep { uc($_) ne $_ } keys %hash ) {
    my $newkey = uc $key;
    $hash{$newkey} = delete $hash{$key};
}
于 2008-11-21T20:43:54.600 回答
0

这会将多级哈希转换为小写

my $lowercaseghash = convertmaptolowercase(\%hash);

sub convertmaptolowercase(){
    my $output=$_[0];
    while(my($key,$value) = each(%$output)){
        my $ref;
        if(ref($value) eq "HASH"){
            $ref=convertmaptolowercase($value);
        } else {
           $ref=$value;
        }
        delete $output->{$key}; #Removing the existing key
        $key = lc $key;
        $output->{$key}=$ref; #Adding new key
    }
    return $output;
}
于 2017-03-31T21:10:23.590 回答