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

$SC = "example.pl"; if ($0 =~ m/(.*)$SC/i){ $dir = $1; print $dir."\n";}

$0 outputs the current directory with the filename being ran, which I'd like to match and remove down to the root directory for any includes that are needed.

Lets say $0 = C:\main1\example.pl using the line above it would change to C:\main1\ cutting off the filename which is good.

Now say the same script was ran from C:\main1\sub1\example.pl my $dir output would be C:\main1\sub1\ but I need that to also be C:\main1\ (the first dir in the output)

So my question is can I match or replace the string in a way that no matter how deep its run the output it cuts off anything past the second \ to keep it no deeper than C:\main1\ ?

Basicly any files that need to be written or read will be in the first dir (C:\main1\) and all subdirs need to be able to point there without using chdir specificly to it or inputting a static directory name. Also the lowest dir will not always have a number so it can't match on numeric followed by a slash or anything to that effect.

Please let me know if this is unclear, thanks in advance for any help.

Replies are listed 'Best First'.
Re: Perl match to cut off after second occurrence
by thenaz (Beadle) on Aug 09, 2011 at 20:51 UTC

    Try this:

    (my $dir = $0) =~ s/([^\\]+\\([^\\]+\\)?)?.*$SC/$1/;
Re: Perl match to cut off after second occurrence
by happy.barney (Friar) on Aug 10, 2011 at 09:00 UTC
    my $STOP_AFTER_MATCH = 2; (undef, undef, my $dir) = split /\\/, $0, $STOP_AFTER_MATCH + 1;
Re: Perl match to cut off after second occurrence
by shadowfox (Beadle) on Aug 10, 2011 at 12:56 UTC

    I like thenaz's suggestion, it works, a good one liner. I didn't test yours happy.barney but thanks for offering another option.

    I came up with a very crude alternative last night but its clear I was barking up the wrong tree because it took a lot more code. I could easily do the first or last occourance but those in between was really throwing me how to do with proper syntax.

    Thanks again to you both,