in reply to Re^2: finding the path of the script running as Win service
in thread finding the path of the script running as Win service

$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

Replies are listed 'Best First'.
Re^4: finding the path of the script running as Win service
by punkish (Priest) on Jan 05, 2005 at 22:55 UTC
    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.
    Thanks Davido for a nice explanation. The above is the only part that is confusing me. Shouldn't the entire pattern be grouped as in s/(\\[^\\]*)$// otherwise what prevents the above from catching everything starting from the very first \ all the way to the end?

    Note: File::Basename does not work in my situation because of the Win service involved. See my OP above.