string split problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Gangreen
    New Member
    • Feb 2008
    • 98

    string split problem

    Hi, I'm new to Perl but I have some experience in other languages.
    Anyway I need to split a string on the character "|".

    let's say our string is "one|two|th ree"

    when I try the following code:

    [CODE=perl] @fields = split('|' , $line); [/CODE]

    My line gets splitted into serperated letters instead of one two and three. Same when I replace '|' with /|/

    when I replace the | with a space in my string, and do thesame in my split-code:
    [CODE=perl]
    $line = "one two three";
    @fields = split(' ' , $line);[/CODE]

    the split does what I expect.
    the elements of the array are:

    $fields[0] : one
    $fields[1] : two
    $fields[2] : three

    So..I'm confused why it works with a space, and not with '|'.. I need to get it to work with '|' ..Can anyone help me?
  • eWish
    Recognized Expert Contributor
    • Jul 2007
    • 973

    #2
    Welcome to TSDN!!

    [CODE=perl]my @array();
    my $string = 'one|two|three' ;
    push @array, split(/\|/, $string);

    print join"\n", @array;[/CODE]

    Comment

    • Gangreen
      New Member
      • Feb 2008
      • 98

      #3
      Ah it's an escape character?
      Thank you!

      Comment

      • KevinADC
        Recognized Expert Specialist
        • Jan 2007
        • 4092

        #4
        The pipe '|' is a special character in a regexp, it means "or". If you want to split on a literal pipe you have to escape it like Kevin shows in his code above. There are many speaical characters used in regular expressions, some reading material if you are interested:

        Beginning Perl
        Pattern Matching and Regular Expressions

        Comment

        • Gangreen
          New Member
          • Feb 2008
          • 98

          #5
          Originally posted by KevinADC
          The pipe '|' is a special character in a regexp, it means "or". If you want to split on a literal pipe you have to escape it like Kevin shows in his code above. There are many speaical characters used in regular expressions, some reading material if you are interested:

          Beginning Perl
          Pattern Matching and Regular Expressions
          I have some books about it, and I'm studying, thanks anyway ;)

          Comment

          Working...