4

I'm creating a script to take regex input from the command line and process it; something like this:

chomp(my $regex = $ARGV[0]);
my $name = '11528734-3.jpg';

$name =~ $regex;

print $name . "\n";

My input into the script is: "s/.jpg/_thumbnail.jpg/g" but $name isn't processing the regex input from the command line.

Any advice on how to make this work?

Thanks!

3
  • You are doing a regex match but not checking whether it succeeded or using its results in any way. What change to you want to happen to $name? Commented Aug 7, 2011 at 5:41
  • 1
    @ysth: I have a feeling that the OP had the argument in the form of s/foo/bar/ and was expecting the =~ $regex to "expand" to =~ s/foo/bar/. Commented Aug 7, 2011 at 5:47
  • Now that you have added what your input is, your title/question is wrong. You are not trying to take a regex from the command line, you are trying to take an operator from the command line. Commented Aug 7, 2011 at 20:23

1 Answer 1

9

Using $name =~ $regex won't change your $name. You have to use the s/// operator to effect any change.

e.g.,

$name =~ s/$pattern/$replacement/;

If you are specifying both the pattern and replacement in the same argument, e.g., in the form of s/foo/bar/, you will have to split them first:

my (undef, $pattern, $replacement) = split '/', $regex;
$name =~ s/$pattern/$replacement/;

Original answer:

Use qr//:

$name =~ qr/$regex/;

You can also just use $name =~ /$regex/, but the qr version is more general, in that you can store the regex object for later use:

$compiled = qr/$regex/;
$name =~ $compiled;
$name =~ s/$compiled/foobar/;

etc.

Sign up to request clarification or add additional context in comments.

3 Comments

shouldn't make any difference; just =~ $regex should work the same
@ysth: In that case, the OP's problem is that he's not using s///, and thus the string isn't modified. :-)
Splitting the string works, but is there any way ... besides maybe using eval ... to pull in whatever regex is sent into the script? I updated the original question with my input into the script as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.