Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

s/// treat rhs as regex

by chuckH (Initiate)
on Sep 07, 2008 at 04:59 UTC ( [id://709603]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://709603]
Approved by lamp
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2025-06-17 01:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.