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

This is just a simplified section of something larger. I'm trying to split a string using a deliminator, which is provided by the user but i must be doing something stupid because it's not splitting as it should. I can't for the life of me figure out what it is. Help?
#!/usr/bin/perl -w $delim = "."; $line = "testing.someting.with.fields"; foreach $field (split(/$delim/, $line)) { print "$field\n"; }
BTW, the deliminator can be any single char if that makes any difference.

Replies are listed 'Best First'.
Re: Split - what am i doing wrong?
by McDarren (Abbot) on May 04, 2009 at 01:32 UTC
    foreach $field (split(/\Q$delim\E/, $line)) {

    Update: See perldoc -q quote

    Darren :)

    PS. The word is "delimiter" ;)

Re: Split - what am i doing wrong?
by roubi (Hermit) on May 04, 2009 at 01:38 UTC
    "." has a special meaning in a regular expression. You need to indicate that you mean the actual "." character instead. See quotemeta.
Re: Split - what am i doing wrong?
by otto (Beadle) on May 04, 2009 at 01:48 UTC

    Examine the split man page and observe that split is taking a pattern for which there may be special characters. These special (meta) characters need to be considered. If the user is not aware of them, then they will not get the splitting they expect. Hence you would would want to un-special them. However if they were aware of them, specifically utilizing them, and you un-special them, again the user will not get what they expect.