如何在Perl中复杂数据结构的每个元素上执行给定的函数? [英] How can I execute a given function on every element of a complicated data structure in Perl?

查看:120
本文介绍了如何在Perl中复杂数据结构的每个元素上执行给定的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解码复杂数据结构中的所有HTML实体。基本上我正在寻找一个超级map()功能。这是我迄今为止所做的:

  sub _html_decode {
my $ self = shift;
我的$ ref = shift;

if(ref($ ref)eqHASH){
$ self-> _html_decode_hash($ ref)
}
if(ref($ ref )eqARRAY){
$ self-> _html_decode_array($ ref);
}

}

sub _html_decode_array {
my $ self = shift;
我的$ ref = shift;

除非(@ $ ref){return;}

foreach(0 ..(标量(@ $ ref) - 1)){
if ($ ref-> [$ _])eqHASH){
$ self-> _html_decode_hash($ ref-> [$ _]);
}
if(ref($ ref-> [$ _])eqARRAY){
$ self> _html_decode_array($ ref-> [$ _]) ;
}
else {
$ ref-> [$ _] = decode_entities($ ref-> [$ _]);
}
}
}

sub _html_decode_hash {
my $ self = shift;
我的$ ref = shift;

除非(%$ ref){return;}

while(my($ k,$ v)= each%$ ref){
if(ref ($ v)eqHASH){
$ self-> _html_decode_hash($ v);
}
如果(ref($ v)eqARRAY){
$ self> _html_decode_array($ v)
}
else {
$ ref-> {$ k} = decode_entities($ v);
}
}
}


解决方案

Data :: Rmap 似乎也这样做。有没有人有这个模块的经验?


I want to decode all the HTML entities in a complicated data structure. Basically I'm looking for a "super map()" function. Here's what I have so far:

sub _html_decode {
    my $self = shift;
    my $ref = shift;

    if (ref($ref) eq "HASH") {
        $self->_html_decode_hash($ref)
    }
    if (ref($ref) eq "ARRAY") {
        $self->_html_decode_array($ref);
    }

}

sub _html_decode_array {
    my $self = shift;
    my $ref = shift;

    unless (@$ref) {return;}

    foreach (0 .. (scalar(@$ref) - 1)) {
        if (ref($ref->[$_]) eq "HASH") {
            $self->_html_decode_hash($ref->[$_]);
        }
        if (ref($ref->[$_]) eq "ARRAY") {
            $self->_html_decode_array($ref->[$_]);
        }
        else {
            $ref->[$_] = decode_entities($ref->[$_]);
        }
    }
}

sub _html_decode_hash {
    my $self = shift;
    my $ref = shift;

    unless (%$ref) {return;}

    while (my ($k, $v) = each %$ref) {
        if (ref($v) eq "HASH") {
            $self->_html_decode_hash($v);
        }
        if (ref($v) eq "ARRAY") {
            $self->_html_decode_array($v)
        }
        else {
            $ref->{$k} = decode_entities($v);
        }
    }
}

解决方案

Data::Rmap seems to do this as well. Does anyone have any experience with this module?

这篇关于如何在Perl中复杂数据结构的每个元素上执行给定的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆