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

because this looks so correct...
@DOMAINS = qw( a.com b.com c.com); foreach $DOMAIN (@DOMAINS) { my ($pre, $suf) = split ("." , $DOMAIN); print $pre; }
but returns nothing

Replies are listed 'Best First'.
Re: i must have forgotten how split works...
by kvale (Monsignor) on Mar 09, 2004 at 17:53 UTC
    The "." is the problem; this is a regexp in disguise. Try
    @DOMAINS = qw( a.com b.com c.com); foreach $DOMAIN (@DOMAINS) { my ($pre, $suf) = split (/\./ , $DOMAIN); print $pre; }

    -Mark

Re: i must have forgotten how split works...
by ambrus (Abbot) on Mar 09, 2004 at 17:51 UTC

    You have. The first arg of split is a regexp, and dot is a regexp metacharacteer.

Re: i must have forgotten how split works...
by Juerd (Abbot) on Mar 09, 2004 at 18:36 UTC

    my ($pre, $suf) = split ("." , $DOMAIN);

    The mistake here is that you used "" for split's first argument. split takes a regex as its first argument. There is one exception: the string ' ' (a single chr(32) character), which is special. Every other string you pass it is interpreted as a regex.

    If you write it as it is interpreted, the mistake is easier to find:

    split /./, $DOMAIN
    It is now clear even to human beings that the . is a regex. It is a metacharacter, so you need to escape it if you want it to be matched literally:
    split /\./, $DOMAIN # or split /[.]/, $DOMAIN

    Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }

Re: i must have forgotten how split works...
by gridlock (Novice) on Mar 09, 2004 at 22:01 UTC
    Aaah - - - regexes in Perl can be both a Boon and a Bane!
    You are splitting on "." - the regex for any character - - so all you are going to get back is what is between each character - - - nothing!
    So split on "\."
    You haven't forgotten how Split works - - just overlooked how regexes work! :)
    /Gridlock a.k.a. Debashis "Codito Ergo Sum"
      So a split on "\."
      No... "\." is still ".". The constructed string should contain a backslash, so you have to write either "\\." or '\.' (or '\\.'). Constructing a regexp in a string is a bit of a pain. That's one of the reasons why qr was invented: qr/\./ will do the right thing, and still return something that can be treated like a string.

      Safer still is to stop playing games and just use the regexp, and write

      my ($pre, $suf) = split /\./, $DOMAIN;