【发布时间】:2015-07-10 03:15:33
【问题描述】:
我目前正在将逗号分隔的 2 元组字符串解析为标量哈希。例如,给定输入:
"ip=192.168.100.1,port=80,file=howdy.php",
我最终得到一个看起来像这样的哈希:
%hash =
{
ip => 192.168.100.1,
port => 80,
file => howdy.php
}
代码运行良好,看起来像这样:
my $paramList = $1;
my @paramTuples = split(/,/, $paramList);
my %hash;
foreach my $paramTuple (@paramTuples) {
my($key, $val) = split(/=/, $paramTuple, 2);
$hash{$key} = $val;
}
我想将功能从仅采用标量扩展到还采用数组和散列。因此,另一个示例输入可能是:
"ips=(192.168.100.1,192.168.100.2),port=80,file=howdy.php,hashthing={key1 => val1, key2 => val2}",
我最终得到一个看起来像这样的哈希:
%hash =
{
ips => (192.168.100.1, 192.168.100.2), # <--- this is an array
port => 80,
file => howdy.php,
hashthing => { key1 => val1, key2 => val2 } # <--- this is a hash
}
我知道我可以逐个字符地解析输入字符串。对于每个元组,我将执行以下操作:如果第一个字符是 (,则解析一个数组。否则,如果第一个字符是 {,则解析散列。否则解析一个标量。
我的一位同事表示,他认为您可以将看起来像 "(red,yellow,blue)" 的字符串转换为数组或将 "{c1 => red, c2 => yellow, c3 => blue}" 转换为带有某种类型转换函数的哈希。如果我走这条路,我可以使用不同的分隔符而不是逗号来分隔我的 2 元组,例如 |。
这在 perl 中可行吗?
【问题讨论】: