chuckH has asked for the wisdom of the Perl Monks concerning the following question:

I wrote a program to do batch renaming on my mp3s. Tried, rather.
c:> rename.pl .*\.mp3 1(\d\d.*) 4$1
What I want is 103_track.mp3 to turn into 403_track.mp3. What I get is a file named 4$1. Thanks in advance.
my $inputMask = $ARGV[0]; my $regexSearch = $ARGV[1]; my $regexReplace= $ARGV[2]; my @files = <*.*>; foreach my $file ( @files ) { if ( $file =~ /$inputMask/ ) { my $oldname = $file; $file =~ s/$regexSearch/$regexReplace/; rename($oldname, $file) or die "$oldname to $file failed: $!"; print "renamed $oldname to $file\n"; } }

Replies are listed 'Best First'.
Re: s/// treat rhs as regex
by jwkrahn (Abbot) on Sep 07, 2008 at 06:30 UTC
Re: s/// treat rhs as regex
by chromatic (Archbishop) on Sep 07, 2008 at 05:12 UTC

    If you're sure that your shell doesn't expand metacharacters (that is, print $regexReplace to make sure it's sane), add the /e flag to your regexp.

      Isn't a double-level of interpolation and eval required?
      perl -wMstrict -e "my $regexSearch = $ARGV[0]; my $regexReplace = $ARGV[1]; my @strings = qw(103_foo 124_bar 109_quux); for my $string (@strings) { my $oldstring = $string; $string =~ s{ $regexSearch }{ qq{qq{$regexReplace}} }xmsee; print \"renamed $oldstring to $string \n\"; } " 1(\d\d.*) 4$1 renamed 103_foo to 403_foo renamed 124_bar to 424_bar renamed 109_quux to 409_quux

      Update: See also printig with variables in text and simple regular expression for further discussion.

        Thank you very much. This is very helpful. I had examined the /e flag but didn't really grasp it. This plus your additions have been very elucidating.