Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 621
Chris Avatar asked Mar 28 '11 19:03

Chris


1 Answers

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;
like image 195
Sean Avatar answered Sep 20 '22 15:09

Sean