Why is split on `|` (pipe) not working as expected?
12,548
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;
Related videos on Youtube
Author by
Chris
Updated on June 04, 2022Comments
-
Chris over 1 year
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
-
Sean over 12 yearsYour input, real output, and expected output would be immensely useful information...
-
tadmc over 12 yearsYou do not have a "delimiter", you have a "separator". A "delimiter" marks the limits, ie. it is at both ends, like double quotes. A "separator" goes in between elements, like the "|" in your example input.
-
-
shawnhcorey over 12 yearsFor more information, see:
perldoc perlretut
,perldoc perlre
and search for /\\Q/ and seeperldoc -f quotemeta
. -
tchrist over 12 yearsThe argument to
split
is not a delimiter, but a separator. -
Sean over 12 yearsNot according to
perldoc -f split
: "Anything matching PATTERN is taken to be a delimiter separating the fields."