in reply to Combining s///

Interesting question. Took me a lot longer than I expected. Did you know you can have perl statements inside your regex?

#!/usr/bin/perl for (@ARGV) { my $d; s! (\d{2})/ (\d{2})/ (\d{2}) (?{ $d = ($3 gt 55)?'19'.$3:'20'.$3;}) !$d/$1/$2!ox; print; print "\n"; }
%./foo 01/02/03 02/14/08 01/02/89 2003/01/02 2008/02/14 1989/01/02


s//----->\t/;$~="JAPH";s//\r<$~~/;{s|~$~-|-~$~|||s |-$~~|$~~-|||s,<$~~,<~$~,,s,~$~>,$~~>,, $|=1,select$,,$,,$,,1e-1;print;redo}

Replies are listed 'Best First'.
Re^2: Combining s///
by ikegami (Patriarch) on Mar 09, 2008 at 23:39 UTC
    More importantly, did you know you can have the substitute expression treated as Perl code using the e modifier?
    for (@ARGV) { s! (\d{2})/ (\d{2})/ (\d{2}) ! my $y = ( $3 > 55 ? '19' : '20' ) . $3; "$y/$1/$2" !xeg; print "$_\n"; }

    More tips:

    • gt is to compare strings. > is to compare numbers.
    • Don't use the o modifier. It only adds disadvantages (no advantages) nowadays.
    • Use local our $var; instead of my $var; for vars outside of regexps used in (?{}) and (??{}). It doesn't always make a difference, but it'll save yourself from subtle errors.
    • Name a variable holding a year something other than $d.

      I didn't know about the 'e' modifier. That would have saved a me a lot of time. Thanks ikegami.

      PS: $d stood in for 'date' and was going to be verbosed later, but later, as is it's want, never showed up.


      s//----->\t/;$~="JAPH";s//\r<$~~/;{s|~$~-|-~$~|||s |-$~~|$~~-|||s,<$~~,<~$~,,s,~$~>,$~~>,, $|=1,select$,,$,,$,,1e-1;print;redo}