perl - Regular expression and hash -
i'm trying transform strings of form 201302_1
2013-02-09
using hash. unfortunately, knowledge of perl rather limited , haven't gotten work yet.
begin { use strict; use warnings; use 5.010; %cycle = qw ( 1 '09' 2 '12' 3 '12' 4 '18' 5 '21' 6 '24' 7 '27' 8 '01' 9 '03' 10 '06' ); } s/(\d{4})(\d{2})_(\d+)$/$1-$2-$cycle{$3}/g
it great if script solved issue of adding 1 month (increasing $2
and $1
) if $3
8, 9 or 10.
i'm running terminal perl -p script.pl sample.txt
edit: ended writing following based on answers seems work:
my %cycle = qw ( 1 09 2 12 3 12 4 18 5 21 6 24 7 27 8 01 9 03 10 06 ); s{(\d{4})(\d{2})_(\d+)1\.csv$}{ @r = (undef, $1, $2, $3); if ($3 > 7) { $r[2] = sprintf("%02d", $r[2]+1); } if ($r[2] > 12) { $r[2] = "01"; $r[1] = $r[1] + 1; } "$r[1]-$r[2]-$cycle{$r[3]}"; }ge;
solving date math regexes not idea, complicated , filled edge cases. use time::piece
instead:
use strict; use warnings; use time::piece; %cycle = qw ( 1 09 2 12 3 12 4 18 5 21 6 24 7 27 8 01 9 03 10 06 ); while (<data>) { chomp; s/_(\d+)$/$cycle{$1}/; $t = time::piece->strptime($_, "%y%m%d"); $t = $t->add_months(1); print $t->strftime("%y-%m-%d"); } __data__ 201302_1
here have guessed (since didn't say) values in %cycle
days, , therefore can treated days. replace digit "day" hash, use strptime
parse date, add month, , print date, using strftime
.
note code assumes whole string date, may need tweak use on other kinds of input.
note can change <data>
<>
use script did before, without -p
switch, i.e.:
perl script.pl sample.txt
Comments
Post a Comment