我有两个字符串:
my $wTime = "00:00-06:00 / 06:00-09:00 / 09:00-17:00 / 17:00-23:00 / 23:00-00:00";
my $wTemp = "17.0 °C / 21.0 °C / 17.0 °C / 21.0 °C / 17.0 °C";
我想将这些字符串连接到散列,其中每个时间刻度的第一部分是一个键,例如:
$hash = (
"00:00" => "17.0 °C",
"06:00" => "21.0 °C",
"09:00" => "17.0 °C",
"17:00" => "21.0 °C",
"23:00" => "17.0 °C"
);
我尝试了一些地图和分裂的变体,但我有一些神秘的结果; - )
%hash = map {split /\s*\/\s*/, $_ } split /-/, $wTime;
答案 0 :(得分:2)
您可以使用List::MoreUtils
zip
/ mesh
function:
my @time_ranges = split ' / ', $wTime;
my @times = map { (split '-', $_)[0] } @time_ranges;
my @temps = split ' / ', $wTemp;
use List::MoreUtils qw(zip);
my %hash = zip @times, @temps;
答案 1 :(得分:2)
还有一种方法:
my $wTime = "00:00-06:00 / 06:00-09:00 / 09:00-17:00 / 17:00-23:00 / 23:00-00:00";
my $wTemp = "17.0 °C / 21.0 °C / 17.0 °C / 21.0 °C / 17.0 °C";
my %h1;
@h1{$wTime=~/([\d:]+)-/g}=split(m! / !,$wTemp);
答案 2 :(得分:1)
这是一个没有List :: MoreUtils的详细解决方案。
my $wTime = "00:00-06:00 / 06:00-09:00 / 09:00-17:00 / 17:00-23:00 / 23:00-00:00";
my $wTemp = "17.0 °C / 21.0 °C / 17.0 °C / 21.0 °C / 17.0 °C";
my @time = map { (split /-/, $_)[0] } split m! / !, $wTime;
my @temp = split m! / !, $wTemp;
my %hash;
for (my $i=0; $i <= $#time; $i++) { # Iterate the times via their index...
# This only works if we have an equal number of temps and times of course.
$hash{$time[$i]} = $temp[$i];
}
答案 3 :(得分:1)
创建两个列表。
my @wTimes = map /([^-]+)/, split qr{ / }, $wTime;
my @wTemps = split qr{ / }, $wTemp;
然后使用哈希切片。
my %hash;
@hash{@wTimes} = @wTemps;