Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

split function for | and \| delimiter

by darklord_999 (Acolyte)
on May 25, 2012 at 18:31 UTC ( [id://972514]=perlquestion: print w/replies, xml ) Need Help??

darklord_999 has asked for the wisdom of the Perl Monks concerning the following question:

I have a file with the values like below:

9454958459|54|AWC XXX|B\|T\|MIN\|MAX\|Air Tree Reg 250 Min|Any(AT)|455|9966004325|..... and so on

I want to split it in a way so that I can get the output into an array with values like below

9454958459

54

AWC XXX

B\|T\|MIN\|MAX\|Air Tree Reg 250 Min

455

9966004325

and so on

How can I use the split function in perl to achieve this ?

Replies are listed 'Best First'.
Re: split function for | and \| delimiter
by moritz (Cardinal) on May 25, 2012 at 18:39 UTC

    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.

      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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://972514]
Approved by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-16 03:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found