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";

我想将这些字符串加入一个哈希,其中每个时间刻度的第一部分是一个键,例如:

$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"
);

我尝试了一些 map 和 split 变体,但我得到了一些神秘的结果;-)

%hash = map {split /\s*\/\s*/, $_ } split /-/, $wTime;
4

4 回答 4

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);
于 2013-02-26T14:28:00.530 回答
2

您可以使用List::MoreUtils zip/mesh功能

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;
于 2013-02-26T13:58:25.607 回答
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];
}
于 2013-02-26T14:06:29.140 回答
1

创建两个列表。

my @wTimes = map /([^-]+)/, split qr{ / }, $wTime;
my @wTemps = split qr{ / }, $wTemp;

然后使用散列片。

my %hash;
@hash{@wTimes} = @wTemps;
于 2013-02-27T02:22:22.737 回答