views:

531

answers:

3

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

+6  A: 
split /\Q$_[2]/, $_[1]
Tanktalus
You are right this is one of the ways I can do it but my tick has to goto the other guy because his worked perfectly off the bat. This generated an error.
Robert Massaioli
No "@fs = " and no semicolon? That's all I can think of (besides PEBKAC). Otherwise its just as good as the other answer.
runrig
Sorry, It was my fault, It works just fine. However, friedo did give alot more information and description so I do not feel too bad about selecting his as the accepted answer; I am sorry, but I will leave my choice as is.runrig: There is no reason to say the PEBKAC; I'm obviously new.
Robert Massaioli
I'm not complaining about choice of "correct" answer, merely seeing if my post needed updating ;-)
Tanktalus
+13  A: 

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.

friedo
Thankyou, It worked right of the bat. Problem solved. One tick for you.
Robert Massaioli
+1  A: 

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) = @_;
  # ...
}
Thanks, I should think about this but I'm pretty new to Perl and I'm finding that I'm treating it a little too much like C. So thanks for the heads up.
Robert Massaioli