I have a sub I use to build a name of a "test case" during an automation run. This name is a string that includes the directory of the Perl .pl file, as well as the file name with the suffix (.pl) stripped off.

So a file with the path 'C:\Tools\scripts\Test\Foo.pl' would produce the string 'Test - Foo'

here is my current sub, which works for me as long as there is no directory between 'Test' and 'Foo':

sub ScriptName { my ($self) = @_; my $name = Win32::GetFullPathName($0); my $dirChop = substr( $name, index($name,'\\scripts\\')+9 ); my $dir = substr( $dirChop, 0, index($dirChop,'\\') ); my $clean = substr( $name, rindex($name,'\\')+1, rindex($name,'.')-(rindex($name,'\\')+1) ); return "$dir - $clean" }

This will totally ignore the sub-directory in the path 'C:\Tools\scripts\Test\Unstable\Foo.pl', where I would like it to return the string 'Test - Unstable - Foo'... but I am no regex pro.

I am looking for a couple pointers:
  1. Can this be cleaned up with regex?
  2. How can I capture a subdirectory (if it exists) too (without losing current functionality)?

In reply to Need to capture an optional sub-directory name by technojosh

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.