Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using perl, how do you process a regex taken from command line input?

Tags:

regex

perl

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!

like image 366
Francis Lewis Avatar asked Jan 20 '23 01:01

Francis Lewis


1 Answers

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.

like image 127
Chris Jester-Young Avatar answered Feb 18 '23 05:02

Chris Jester-Young