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

I am trying to use the 'split' function to separate a string into 2 variables. The string "$dir" contains something like: \\server\share//folder/subfolder.

I cannot figure out how to split these with the split function. Here is the peice of code I have right now, although it doesn't work.

($rootdir,$userdir) = split / // /,$dir;

Does anyone have any suggestions?

Replies are listed 'Best First'.
Re: Split by "//"
by Zaxo (Archbishop) on Jun 24, 2003 at 17:55 UTC

    You need to remove spaces and escape the slashes with backwhacks: ($rootdir,$userdir) = split /\/\//,$dir;

    After Compline,
    Zaxo

Re: Split by "//"
by Tomte (Priest) on Jun 24, 2003 at 17:57 UTC

    #!/usr/bin/perl my $test='\\\\server\\share//folder/subfolder'; my ($share,$dir) = split(m!//!, $test); print $share, " .. " , $dir; __END__ \\server\share .. folder/subfolder

    You can either escape the '/'s inside the regexp, or give an explizit 'm' and use whatever you like as regexp-delimiter, as I have done in the snippet above

    regards,
    tomte


    Hlade's Law:

    If you have a difficult task, give it to a lazy person --
    they will find an easier way to do it.

Re: Split by "//"
by artist (Parson) on Jun 24, 2003 at 17:56 UTC
    You can go further from here
    $_ = q(\\server\share//folder/subfolder); my($rootdir,$userdir)= split m[\Q//\E]; print join "\n", ($rootdir,$userdir),"\n";

    artist

Re: Split by "//"
by Hofmator (Curate) on Jun 25, 2003 at 11:54 UTC
    Another possibility: ($rootdir,$userdir) = split '//', $dir; Caveat: it looks like a string but is treated like a regex, meaning special characters like ., *, $, etc. are still special (have their normal regex meaning). But / is not special, so no problem there.

    The slash / is special in your code, as it delimits the regex, cf. Tomte's post on how to choose different regex delimiter.

    -- Hofmator