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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With