Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle every ASCII character (including regex special characters) in a Perl regex?

I have the following code in Perl:

if (index ($retval, $_[2]) != -1) {
    @fs = split ($_[2], $_[1]);

$_[2] is the delimiter variable and $_[1] is the string that the delimiter may exist in. ($_[0] is used elsewhere) You may have guessed that this code is in a subroutine by those variable names.

Anyway, onto my question, when my delimiter is something innocuous like 'a' or ':' the code works like it should. However, when it is something that would get parsed by Perl regex, like a '\' character, then it does not work like it is supposed to. This makes sense because in the split function Perl would see something like:

split (/\/, $_[1]); 

which makes no sense to it at all because it would want this:

split (/\//, $_[1]);

So with all of that in mind my question, that I cannot answer, is this: "How do I make it so that any delimiter that I put into $_[2], or all the ASCII characters, gets treated as the character it is supposed to be and not interpreted as something else?"

Thanks in advance,

Robert

like image 720
Robert Massaioli Avatar asked Dec 01 '22 12:12

Robert Massaioli


2 Answers

You can use quotemeta to escape $_[2] properly so it will work in the regex without getting mangled. This should do it:

my $quoted = quotemeta $_[2];
@fs = split( $quoted, $_[1] );

Alternatively, you can use \Q in your regex to escape it. See "Escape Sequences" in perlre.

like image 83
friedo Avatar answered Dec 04 '22 15:12

friedo


split /\Q$_[2]/, $_[1]
like image 42
Tanktalus Avatar answered Dec 04 '22 15:12

Tanktalus