Procecdure #
1s/^(\d{4})-(\d{2})-(\d{2})$/timegm_posix(0,0,18,$3,$2-1,$1-1900)/e
Comments #
Use a regex with capture groups to isolate the year, month, and date, then
substitute substitute the line with the scalar returned by timegm_posix()
.
The /e
allows for the right side / replacement in the regex to be an
expression rather than text.
Examples #
Run this script as a one-liner.
$ echo "1999-04-01" | \
perl -MTime::Local=timegm_posix -pE 's/^(\d{4})-(\d{2})-(\d{2})$/timegm_posix(0,0,18,$3,$2-1,$1-1900)/e'
Comparing performance with a typical shell script.
Create a bunch of dates.
$ perl -E 'map { printf "%04d-%02d-%02d\n", (1992..2022)[rand 30], (1..12)[rand 12], (01..28)[rand 28] } 1..1000' \
> dates.txt"
Create the shell script
$ cat epoch.sh << EOF
while read d; do date -d "${d} 18:00:00Z" done
EOF
Time the execution
$ time bash epoch.sh < dates.txt >/dev/null
0.79s user 0.31s system 103% cpu 1.066 total"
$ time perl epoch.pl dates.txt >/dev/null
0.03s user 0.01s system 96% cpu 0.050 total"
See Also #
- Perl operator: s/PATTERN/REPLACEMENT/options
- Perl function: timegm_posix()
- Perl runtime: -M'module'