Reputation: 13477
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
Upvotes: 4
Views: 1257
Reputation: 4029
As a side note, I'm suspecting that the $_[1]
and $_[2]
variables refer to the automatically passed in @_
array of a sub.
It's helpful - would have saved you quite some explaining here and made your code more understandable by itself - and common practice to use something like the following at the beginning of the sub:
sub mysub {
my ($param1, $string, $delim) = @_;
# ...
}
Upvotes: 1
Reputation: 66957
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.
Upvotes: 13