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
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.
split /\Q$_[2]/, $_[1]
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