Why is split on `|` (pipe) not working as expected?

Chris picture Chris · Mar 28, 2011 · Viewed 12.3k times · Source

I have a string that I want to split. But the separator is determined at runtime and so I need to pass it as a variable.

Something like my @fields = split(/$delimiter/,$string); doesn't work. Any thoughts?


Input:

abcd|efgh|23

Expected Output:

abcd
efgh
23

Answer

Sean picture Sean · Mar 28, 2011

You need to escape your delimiter, since it's a special character in regular expressions.

Option 1:

$delimiter = quotemeta($delimiter);
my @fields = split /$delimiter/, $string;

Option 2:

my @fields = split /\Q$delimiter/, $string;