By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,852 Members | 1,410 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,852 IT Pros & Developers. It's quick & easy.

string split problem

P: 98
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|three"

when I try the following code:

Expand|Select|Wrap|Line Numbers
  1.  @fields = split('|' , $line); 
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:
Expand|Select|Wrap|Line Numbers
  1. $line = "one two three";
  2. @fields = split(' ' , $line);
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?
Feb 24 '08 #1
Share this Question
Share on Google+
4 Replies


eWish
Expert 100+
P: 971
Welcome to TSDN!!

Expand|Select|Wrap|Line Numbers
  1. my @array();
  2. my $string = 'one|two|three';
  3. push @array, split(/\|/, $string);
  4.  
  5. print join"\n", @array;
Feb 24 '08 #2

P: 98
Ah it's an escape character?
Thank you!
Feb 24 '08 #3

KevinADC
Expert 2.5K+
P: 4,059
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
Feb 24 '08 #4

P: 98
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 ;)
Feb 25 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.