views:

339

answers:

2

My code used to work fine, and now it's breaking. A reduction of the problem is the following: I want to split a source string (from a database, but that's not important) at a separator. The separator is not fixed, but user provided, in a string. I used to do that:

@results = split($splitString, $sourceStr);

But this breaks when the users asks for the plus sign (+) as a separator. The message is a bit cryptic:

Quantifier follows nothing in regex; marked by <-- HERE in m/+ <-- HERE

My understanding is that it breaks because split doesn't expect a string, but a regexp. However, I can't manage to find a way to escape the $splitString in a way that works. Here is my toy example:

  my $s = 'string 1 + $splitChar + string 2';
  my $splitChar = "+";
  my @result = split(/\\$splitChar/, $s);

  print "num of results ".scalar(@result)."\n";
  foreach my $value (@result) {
    print "$value\n"; 
  }

But it doesn't split at all. I tried a number of variations, none of which worked. Note that the user-specified separator probably is limited to one character, but a multi-character solution would be better.

(and yes, I could write my own specialized split function, but it's not the point).

(the $splitChar in the single quoted string example is on purpose, I suppose it's clear why).

+14  A: 

The first argument to split is a pattern:

#!/usr/bin/perl

use strict;
use warnings;

my $sep = '+';
my $source = 'one+two+three';

my @results = split /\Q$sep\E/, $source;

use Data::Dumper;
print Dumper \@results;

See also perldoc -q "quote a variable".

Sinan Ünür
Great, I didn't know about \Q and \E. That's what I needed. Many thanks
Jean-Denis Muys
+5  A: 

The problem is that + is used as a metacharacter to indicate 'one or more' of the preceding items (so you are asking for one or more, without specifying what it is you want)

Sinan's answer is a good one, and check out the quotemeta function as well.

Cebjyre