On Fri, Jun 5, 2009 at 15:48, Balazs Wellisch <bal...@neusolutions.com> wrote:
> Hi all,
>
> I'm using a regular expression to rename some files I'm working with.
> It works well and does exactly what I need.
>
> $name =~ s/(\S+)_(\d+)\.(\S*)$/$2\/videos\/$1\.$3/i;
>
> However, I would like to read this pattern from an ini file instead of
> having it hard coded into the program. So, the code would be modified
> something like this:
>
> $pattern = 's/(\S+)_(\d+)\.(\S*)$/$2\/videos\/$1\.$3/i';
> $name =~ $pattern;
>
> But this doesn't work. How do I get perl to evaluate $pattern in this context?
>
> I also tried...
>
> $name =~ qr/$pattern/;
>
> ...but that doesn't seem to work either.
>
> Any ideas would be much appreciated!
snip

s/REGEX/STRING/ is not a regex, it has two parts: the regex and the
replacement string.  You can use qr// to compile the regex part, but
not the string part.  In order to get the replacement to work you must
use /ee to get it to eval your string as code (so remember to use
valid Perl code as the second part).  Also, never trust regexes or
code from untrusted parties (like say over the web).  A config file
should be somewhat safe, but I would rethink your design if people
other than the developers are going to use the config file.

#!/usr/bin/perl

use strict;
use warnings;

my @replace;
while (<DATA>) {
        my ($re, $string) = split " => ";
        push @replace, [ qr/$re/, $string ];
}

while (<>) {
        for my $re (@replace) {
                s/$re->[0]/$re->[1]/iee;
        }
        print;
}

__DATA__
(\S+)_([0-9]+)[.](\S*)$ => "2/videos/$1.$3"



-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to