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

Hi Monks!! I am not able to split a string on special character "|" if it is stored in a variable..Please help me out..My test script is
#!/usr/bin/perl $var = "21|23|24~34|45|56~"; my @arr = split("",$var); $sep = $arr[2]; $ele = $arr[8]; my @arr = split($ele,$var);
but I can split it directly using
my @arr = split('/\|/',$var);

Replies are listed 'Best First'.
Re: problem in splitting on special character
by ikegami (Patriarch) on Aug 30, 2007 at 04:17 UTC

    The first argument of split is either a compiled regexp or a regexp string. | is a special character in regular expressions, so it must be escaped if you mean it literally.

    Some solutions:

    split(/\|/, ...)
    my $re = qr/\|/; split($re, ...)
    my $re = "\\|"; # \| split($re, ...)
    my $str = "|"; # | my $re = quotemeta($str); # \| split($re, ...)

    In your case, the last alternative is the desired one. You want to convert a text into a regexp, and quotemeta will do that for you.

    my $sep = $arr[2]; split(quotemeta($sep), ...)
      hey Thanx to both of you...
Re: problem in splitting on special character
by GrandFather (Saint) on Aug 30, 2007 at 04:16 UTC

    Your second split is attempting to use ~ as the match character, not |. Did you intend to use $sep? Actually, even that won't do what you want because you need to quote | (it is a regex meta character). Something like:

    @arr = split /\Q$sep\E/, $var;

    DWIM is Perl's answer to Gödel
Re: problem in splitting on special character
by bruceb3 (Pilgrim) on Aug 30, 2007 at 04:25 UTC
    You need to quote the expression used for the split.
    my @arr = split /\Q$ele\E/, $var;

    BTW, you have $ele when you should have $sep, unless you plan on splitting on the "~" character. You did say in your question that you wanted split on the "|" character?

    In this case you probably don't need the \E since you are quoting the entire regex anyway.

    #!/usr/bin/perl # vim: sw=4 use strict; use warnings; use Data::Dumper; my $var = "21|23|24~|34|45|56~"; my @arr = split("", $var); my $sep = $arr[2]; my $ele = $arr[8]; my @ar = split(/\Q$sep\E/, $var); print Dumper \@ar; bruce:1:~/tmp $ ./p.pl $VAR1 = [ '21', '23', '24~', '34', '45', '56~' ]; bruce:1:~/tmp $