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

Aloha Monks,

I'm tying to use split accrding to "\\"
@file = split ("\\",$file);

but I get htis error message:

Trailing \ in regex m/\/

How Do I solve this?
I'm a bit lost
Nir

Replies are listed 'Best First'.
Re: Split according to \
by bart (Canon) on May 05, 2005 at 08:39 UTC
    We've settled this in the chatterbox, but I'll go into more detail here.

    Use the regex syntax, /\\/, not the string syntax. You see, Perl needs to see two backslashes in the regex, but if you use the string syntax, you already lose one before the regex engines gets to see it. If you use a regex, it's passed like you see it in the source code.

    print "\\"; # a backslash
    This prints a single backslash. So that's what the regex engine see, too. If you had used 4 backslashes, then it would have worked.
    print "\\\\"; # two backslashes
    @file = split ("\\\\",$file); # split on a single backslash

    It's the same situation in PHP, BTW, where there is no native built-in syntax for regexes, but only strings. In Perl, it's easier to use a regex, and no reason not to. And you don't need to use that many parens.

    @file = split /\\/,$file; # split on a single backslash
Re: Split according to \
by TedPride (Priest) on May 05, 2005 at 08:23 UTC
    You're using PHP syntax. Perl uses something more like:
    @file = split (/\\/,$file);
Re: Split according to \
by sh1tn (Priest) on May 05, 2005 at 11:00 UTC
    my $split_reg = qr{\\{2}};# 2 repetitions # or my $split_reg = qr{\\{1}};# 1 repetition @file = split /$split_reg/, $file;