in reply to split function for | and \| delimiter

The most robust solution is probably to use Text::CSV, which can handle delimiters and escaped delimiters.

If you want to do it with a regex, you must split on a vertical bar that is not preceeded by a backslash.

Since both the vertical bar and the backslash are meta characters in regexes, you need to backslash-escape both:

my @chunks = split /(?<!\\)\|/, $yourstring;

See perlretut for more details.

Replies are listed 'Best First'.
Re^2: split function for | and \| delimiter
by xorl (Deacon) on May 25, 2012 at 18:52 UTC
Re^2: split function for | and \| delimiter
by darklord_999 (Acolyte) on May 25, 2012 at 19:16 UTC

    Thanks for replying. I tried your idea but it didn't work. I got the output like

    $str="9454958459|54|AWC XXX|B\|T\|MIN\|MAX\|Air Tree Reg 250 Min|Any(A +T)|455|9966004325|"; @arr=split /(?<!\\)\|/, $str; print "$_ \n" foreach(@arr);

    and the output is

    9454958459

    54

    AWC XXX

    B

    T

    MIN

    MAX

    Air Tree Reg 250 Min

    455

    9966004325

      Use single quotes to prevent interpolation of $str:
      use warnings; use strict; my $str='9454958459|54|AWC XXX|B\|T\|MIN\|MAX\|Air Tree Reg 250 Min|An +y(AT)|455|9966004325|'; my @arr=split /(?<!\\)\|/, $str; print "$_ \n" foreach(@arr); __END__ 9454958459 54 AWC XXX B\|T\|MIN\|MAX\|Air Tree Reg 250 Min Any(AT) 455 9966004325

        Yes this works. Thanks for your help :)