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

wow! What is going on here? ( our $path = $0 ) =~ s/\\[^\\]*$//;

I can't even grok the above. That said, wrt the second part, I want to really do

( our $path = $0 ) =~ s/\\[^\\]*$//; BEGIN { print $path; }
Why does $path declared before the BEGIN block not be visible inside the BEGIN block?

Replies are listed 'Best First'.
Re^3: finding the path of the script running as Win service
by davido (Cardinal) on Jan 05, 2005 at 22:47 UTC

    $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

      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.

Re^3: finding the path of the script running as Win service
by borisz (Canon) on Jan 05, 2005 at 22:40 UTC
    what you might want is:
    BEGIN { ( our $path = $0 ) =~ s/\\[^\\]*$//; }
    Now you can use $path everywhere.
    The BEGIN block is done at compiletime. The rest is done at runtime. Perl compiles your script and runs the compiled then.
    Read perldoc perlmod.
    Boris