Chris
Chris

Reputation: 3043

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

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

Upvotes: 10

Views: 12959

Answers (1)

Sean
Sean

Reputation: 29800

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;

Upvotes: 19

Related Questions