Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Problem using | char as delimiter for split

by alandev (Scribe)
on Aug 29, 2006 at 13:07 UTC ( [id://570147] : perlquestion . print w/replies, xml ) Need Help??

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

hi monks

i expected the below code to produce result

0427320060001
39104
20020
190
2
but it produces 04273. where i am goin wrong?

the code
$a="0427320060001|39104|20020|190|2"; my($num1,$num2,$num3,$num4,$num5)=split(/|/,$a); print $num1; print $num2; print $num3; print $num4; print $num5;
thanks in advance

2006-08-29 Retitled by jeffa, as per Monastery guidelines
Original title: 'Split ??'

Replies are listed 'Best First'.
Re: Problem using | char as delimiter for split
by imp (Priest) on Aug 29, 2006 at 13:13 UTC
    | is the alternation operator within a regular expression. For example foo|bar matches "foo" or "bar".

    If you want to split using it, you need to escape it with a \

    my($num1,$num2,$num3,$num4,$num5)=split(/\|/,$a);
Re: Problem using | char as delimiter for split
by philcrow (Priest) on Aug 29, 2006 at 13:15 UTC
    You have two main problems. First | is special in regexes, escpae it:
    ...split /\|/, $a;
    Second, on output, you are not putting anything between the numbers, add some new lines:
    print "$num1\n"; ...
    Phil
Re: Problem using | char as delimiter for split
by prasadbabu (Prior) on Aug 29, 2006 at 13:14 UTC

    '|' is a special character in Perl, so you have to backslash it as '\|' to make it as normal pipe character. Take a look at perlre.

    $a="0427320060001|39104|20020|190|2"; my ($num1, $num2,$num3,$num4,$num5)=split(/\|/,$a); print "$num1\n$num2\n$num3\n$num4\n$num5"; prints: 0427320060001 39104 20020 190 2

    Prasad

Re: Problem using | char as delimiter for split
by ForgotPasswordAgain (Priest) on Aug 29, 2006 at 13:14 UTC
    You want to put a backslash before the pipe (|). What you wrote says to split on '' or '', which will match between the characters, so you get the first five.
Re: Problem using | char as delimiter for split
by dark314 (Sexton) on Aug 29, 2006 at 16:28 UTC
    Usually what I do is when its a weird character(meaning non-alphanumeric), I use the backslash, This might not always apply but its a good rule of thumb. In either case, reading the 3 chapters in Learning Perl is probably a good idea (or re-reading). For every special character you learn how to use, you can be certain to add a backslash if your matching that character. :)