将字符串拆分为散列的散列(perl) [英] Split string into a hash of hashes (perl)

查看:61
本文介绍了将字符串拆分为散列的散列(perl)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此刻我有点困惑..

我正在寻找一种方法,可以在递归散列中编写一个包含不确定字数(以斜杠分隔)的字符串.

I am looking for a way to write a string with an indefinite number of words (separated by a slash) in a recursive hash.

这些字符串"是从文本数据库中输出的.

These "strings" are output from a text database.

给定是例如办公室/1/硬件/鼠标/计数/200"

Given is for example "office/1/hardware/mouse/count/200"

下一个可以更长或更短..

the next one can be longer or shorter..

这必须从它创建:

{
    office {
        1{
            hardware {
                mouse {
                    count => 200
                }
            }
        }
    }
}

有什么想法吗?

推荐答案

向后工作.拆分字符串.使用最后两个元素来制作最里面的散列.当存在更多词时,将每个词作为新散列的键,并将内部散列作为其值.

Work backwards. Split the string. Use the last two elements to make the inner-most hash. While more words exist, make each one the key of a new hash, with the inner hash as its value.

my $s = "office/1/hardware/mouse/count/200";

my @word = split(/\//, $s);

# Bottom level taken explicitly
my $val = pop @word;
my $key = pop @word;

my $h = { $key => $val };

while ( my $key = pop @word )
{
    $h = { $key => $h };
}

这篇关于将字符串拆分为散列的散列(perl)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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