Hi everyone !!

Here is an easy one for you !

I have a path to a file like this : "D:\My Documents\Document.txt" and I want to get only the part with "D:\My Documents". Right now I am doing this, but it does not seem quite efficient:
my $path = "D:/a directory/another directory/.../a file"; my @tmp = split(/\//, $path); my $last = @tmp - 1; $path =~ /\/$tmp[$last]/; my $dir = $PREMATCH; my $fileName = $tmp[$last];
It works but I feel I could use a regex for it instead of a split, or maybe something else than using a match.
So, the question is: is there a way to match only the last occurence of a character (like "/") in a string or any better way to get the directory of the file path?

All ideas are welcomed !


In reply to match only last character of a kind by duc

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.