$0 is the special variable that "contains the name of the program being executed." It's nmemonic is "$PROGRAM_NAME".

'our $path = $0' assigns $0 to $path. This is a legal request, even as the lvalue of a =~ operator. And the s/// operator then acts upon $path.

Read it in this order:

  1. Declare $path.
  2. Assign $0 to $path
  3. Bind $path to a substitution operator.
  4. Substitute, matching on the last '\' character, followed by any amount (or nothing at all) of non '\' characters. Replace with nothing. Essentially, this strips away the filename and final '\' character, on a system where '\' is the path separator.

Actually, the regexp is a little fragile, and you might be better off using File::Basename's dirname() funtion.

To answer your second question, the BEGIN{} block is executed at an earlier stage, during compilation time instead of runtime. That means that even though the compiler has seen ( our $path = $0 ) before it sees the BEGIN{} block, it executes the begin block before the assignment to $path takes place. Note also that if use strict; is in effect, our enforces a sort of lexical scoping on the usage of $path. That's not really an issue here, but worth mentioning.


Dave


In reply to Re^3: finding the path of the script running as Win service by davido
in thread finding the path of the script running as Win service by punkish

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.