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;
Share:
12,548

Related videos on Youtube

Chris
Author by

Chris

Updated on June 04, 2022

Comments

  • Chris
    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
      Sean over 12 years
      Your input, real output, and expected output would be immensely useful information...
    • tadmc
      tadmc over 12 years
      You 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
    shawnhcorey over 12 years
    For more information, see: perldoc perlretut, perldoc perlre and search for /\\Q/ and see perldoc -f quotemeta.
  • tchrist
    tchrist over 12 years
    The argument to split is not a delimiter, but a separator.
  • Sean
    Sean over 12 years
    Not according to perldoc -f split: "Anything matching PATTERN is taken to be a delimiter separating the fields."

Related