user2111402
user2111402

Reputation: 19

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, e.g.:

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

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

Upvotes: 2

Views: 140

Answers (4)

ikegami
ikegami

Reputation: 385764

Create both lists.

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

Then use a hash slice.

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

Upvotes: 1

simbabque
simbabque

Reputation: 54323

Here's a verbose solution without 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];
}

Upvotes: 1

Guru
Guru

Reputation: 16984

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

Upvotes: 2

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28005

You can use 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;

Upvotes: 2

Related Questions