Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello everyone, I'm trying to use split on a line from a file that uses + sign as a delimiter. Whenever I try this, I get an error where the interpreter thinks I'm trying to use a regexp. For example, this code:

$t = "t+e+s+t";
($a, $b, $c, $d) = split ("+", $t);
Generates this error: "/+/: ?+*{} follows nothing in regexp at w.pl line 2." I'm pretty sure I need something to interpolate the +-sign because plain old quotes " " are not getting it done. Thanks, RT

Replies are listed 'Best First'.
Re: Trouble with +-sign as delimiter
by vroom (His Eminence) on May 02, 2000 at 00:48 UTC
Re: Trouble with +-sign as delimiter
by btrott (Parson) on May 02, 2000 at 00:50 UTC
    The PATTERN specified to split is *always* interpreted as a regex, even if you don't put // around it (except, I guess, for the special case of ' '--more in the split manpage).

    The solution is to escape the "+":

    ($a, $b, $c, $d) = split /\+/, $t;
Re: Trouble with +-sign as delimiter
by perlmonkey (Hermit) on May 02, 2000 at 04:55 UTC
    You can also use the \Q and \E in the regular expression to make sure charaters are interpreted literally;
    $delimeter = "+"; $t = "t+e+s+t"; ($a, $b, $c, $d) = split(/\Q$delimeter\E/, $t); ### or ### ($a, $b, $c, $d) = split(/\Q+\E/, $t);
    But for the last one just using /\+/ is obviously easier.