in reply to split/map weirdness: empty strings vs undef

One problem is that you're splitting on '\' when the delimeter is '|'. This results in a single-element array, holding the complete string you tried to split. When you apply a subscript of 4, you get an undefined value.

Try this:

map { print defined($_) ? "def\n" : "undef\n" } split(/|/, "2|3|||||");

Bug! That should be split(/\|/, ...) See below.

Replies are listed 'Best First'.
Re: Re: split/map weirdness: empty strings vs undef
by blakem (Monsignor) on Oct 04, 2002 at 20:05 UTC
    You'll need to escape the pipe, though, because its a special char (alternation) in the regex...
    split(/\|/, "2|3|||||")

    -Blake

      You'll need to escape the pipe, though, because its a special char (alternation) in the regex...

      Quite so. And note that   split(/\|/, "2|3||||"); gives a different result than   split('|', "2|3||||"); Consult perlfunc for details. You probably want to be using the latter form, as it retains empty fields.

        Uhm... split(/\|/, "2|3||||"); is different from split('|', "2|3||||"); only because that pipe isn't escaped in the second one. Perl will split on that as if it were a pattern. In other words, that's broken in the same way as your original one. Note that splitting on a literal space is a special case. This isn't.

        $ perl -le '$_="2|3|||||"; @a = split q(|); print "($_)" for @a' (2) (|) (3) (|) (|) (|) (|) (|) $ perl -le '$_="2|3|||||"; @a = split /|/; print "($_)" for @a' (2) (|) (3) (|) (|) (|) (|) (|)
        -sauoq
        "My two cents aren't worth a dime.";
        
Re: Re: split/map weirdness: empty strings vs undef
by sauoq (Abbot) on Oct 04, 2002 at 20:12 UTC

    Almost. As blakem said, you have to escape the pipe. Maybe more importantly though, the trailing empty fields will disappear in a puff of smoke.

    perl -le 'map { print defined($_) ? "def" : "undef" } split(/\|/, "2|3 +|||||"); def def
    -sauoq
    "My two cents aren't worth a dime.";