Hello Perl Monks,
I am trying to solve a text parsing problem where I would like to transform the following data:
Mon 0100 Mon 0700 Tue 0700 Wen 0100 Wen 0700 Thu 0100 Thu 0700 Fri 0100 Fri 0700 Sat 0100 Sun 0100 Sun 0700
to
Mon Tue Wen Thu Fri Sat Sun 0100 X X X X X X 0700 X X X X X X
It is basically transposing of columns where I would list the time field just once and for each day of the week found in the data, if the time existed, I would mark that column with X. If the time did not exist for that day, I would put a space.
I was able to solve the problem by doing:
perl -lane ' $h{$F[0]}++ or push @days, $F[0]; $h{$F[1]}++ or push @time, $F[1]; $data{$F[0],$F[1]}++ }{ print "\t\t", join "\t", @days; for $t (@time) { print $t, "\t\t", join "\t", map { $data{$_,$t} ? "X" : " " } +@days; } ' file
However, I was trying to learn chaining of map function and running in to some issues. My last attempt at chaining maps is:
perl -ane ' $h{$F[0]}++ or push @days, $F[0]; $h{$F[1]}++ or push @time, $F[1]; $data{$F[0],$F[1]}++ }{ print "\t\t", join "\t", @days; print "\n"; print for join "\t", map { $t = $_ ; (map { $data{$_,$t} ? "X" : " + " } @days) } @time; ' file
But I am struggling to print each element of time array just once and then iterate over the hash to print X or space if the key exists.
Looking forward to your wisdom.
Regards
In reply to Trouble Chaining map function by jaypal
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |