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? | [reply] [d/l] [select] |
$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:
- Declare $path.
- Assign $0 to $path
- Bind $path to a substitution operator.
- 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.
| [reply] [d/l] [select] |
| [reply] [d/l] |
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.
| [reply] [d/l] [select] |