简体   繁体   English

如何在Perl中将两个字符串转换为哈希?

[英]How can I convert two strings to a hash in perl?

i have two strings: 我有两个字符串:

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

I would like to join these strings to a hash, where the first part of each timescale is a key, eg: 我想将这些字符串连接到一个哈希表中,每个时标的第一部分是一个键,例如:

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

I have tried some variants of map and split but i've got some mysterious results ;-) 我尝试了map和split的一些变体,但得到了一些神秘的结果;-)

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

You can use List::MoreUtils zip / mesh function : 您可以使用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;

One more way: 另一种方式:

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

Here's a verbose solution without List::MoreUtils. 这是一个没有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];
}

Create both lists. 创建两个列表。

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

Then use a hash slice. 然后使用哈希切片。

my %hash;
@hash{@wTimes} = @wTemps;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM