in reply to Wierd funky problems with split

but it doesnt work right.

I got burned by this a couple of months ago. The first argument to split, with one exception, is a regular expression, whether it looks like one or not. And '|' has a special meaning in regular expressions. Change   ($pointer, $id, $title) = split("||"); to   ($pointer, $id, $title) = split "\|\|"; and you'll get better results.

Replies are listed 'Best First'.
Re: Re: Wierd funky problems with split
by pg (Canon) on Jan 02, 2003 at 04:44 UTC
    Your answer is not quite right. test with this:
    $a = "12||23||34||45"; @a = split("\|\|", $a); print join(",", @a);
    Instead of giving you,
    12,23,34,45
    It gives you
    1,2,|,|,2,3,|,|,3,4,|,|,4,5
    You have to say:
    $a = "12||23||34||45"; @a = split(/\|\|/, $a); print join(",", @a);
    Or, if you want to use quots, say:
    $a = "12||23||34||45"; @a = split("\\|\\|", $a); print join(",", @a);
    The reason is simple:
    1. For that "|", you need to escape it within regexp, but not within quots.
    2. For that "\", you have to escape it within quots.
    So if you say "\\|",
    1. First it is being intepreted by the quots as "\|",
    2. Then it is being further interpreted by the regexp as "|".
Re: Re: Wierd funky problems with split
by jdporter (Paladin) on Jan 02, 2003 at 03:50 UTC
    Right on! And just to emphasize it in your own mind (and that of those who will come after you), you should always write it like a regex, e.g. split /\|\|/;

    Just a stylistic point...

    jdporter
    The 6th Rule of Perl Club is -- There is no Rule #6.