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

I think that I found a strange exception in the split function, and was wondering if someone can tell me why this happens. Basically, I have a very simple split finction:
($acc_num, $ofname,$junk,$olname,$junk2) = split /|/, $line, 5;
to split up a pipe delimited list. Like this:
AccountKey|Given|MiddleName1|Surname|GeoCity
Instead of the expected results, I get the result of having each variable in the array being one digit of the AccountKey. I have never seen this before and understand that I can sub commas for pipes rather quickly, but I was hoping to see if anyone knew why pipes are so special in this context.
Thanks,
cens

Replies are listed 'Best First'.
Re: Splits and pipes
by bobn (Chaplain) on Sep 06, 2003 at 21:23 UTC

    The first argument to split is (usually, and definitely in this case) a regular expression. The pipe symbol | is a metacharacter in regexes meaning 'or' - so you've told split to split off whenever it matches a null character or a null cahracter. This happens between every character.

    I think what you wanted was: ($acc_num, $ofname,$junk,$olname,$junk2) = split /\|/, $line, 5; where the backslash makes the pipe character match literally.

    --Bob Niederman, http://bob-n.com

    All code given here is UNTESTED unless otherwise stated.

      Man, I don't know how I missed that... should have known better. Thanks.

        I don't miss that one much anymore since the day I spent *hours* trying to ffigure out why split(/./, $ip_address) wouldn't work right. Complete aggravation is a good memory aid!

        --Bob Niederman, http://bob-n.com

        All code given here is UNTESTED unless otherwise stated.