[quote=Dieter,07.07.2004, 14:55]
- Ein BEGIN Block ist 'immer' die 'erste Tat' des Compilers
- Ein BEGIN Block wird compiliert und ausgeführt, noch 'bevor' sich der Compiler um den Rest des Programms kümmert
[/quote]
perlmod.pod:
A "BEGIN" subroutine is executed as soon as possible, that
is, the moment it is completely defined, even before the
rest of the containing file is parsed.
d.h. der teil des programms vor dem BEGIN
wird geparsed. somit auch
ein
my $x; vor dem BEGIN-block. siehe beispiel unten mit
strict.
QuoteErgo:
Zum Ausführungszeitpunkt des BEGIN Blocks sind dem Compiler (und damit dem Block) die Inhalte des Hauptprogramms (noch) nicht bekannt, daher ist es dem Block nicht möglich, auf Variablen des Hauptprogramms zuzugreifen
doch, der teil vor BEGIN ist bekannt. noch nicht
ausgeführt, aber bekannt. dazu gehören deklarationen wie my(), our() etc.
Quote- Variablen die innerhalb des BEGIN Blocks mit 'my' deklariert sind, werden vom Hauptprogramm 'nicht' gesehen
ok
Quote- Variablen die innerhalb des BEGIN Blocks mit 'our' deklariert sind, werden vom Hauptprogramm gesehen
ja, wobei aber speziell
print $x;
BEGIN { our $x = 23; }
nicht unter strict läuft, weil das print vorher geparsed wird.
Quote- Variablen die innerhalb des BEGIN Blocks nicht deklariert werden, sind automatisch 'global' und werden vom Hauptprogramm gesehen
was soll das heissen? du meinst also etwa
BEGIN { $x = 1234; }?
in dem fall ist $main::x gemeint, also global, richtig.
aber mit einem
my $x; vorher ist es nicht mehr $main::x, also
nicht global, sondern lexikalisch.
hier der beweis:
tina@tuxedo:~> perl -wle'
my $x; # lexikalisch
BEGIN {
$x = 23;
$y = 42;
}
print "x: $main::x, y: $main::y"'
Name "main::x" used only once: possible typo at -e line 7.
Use of uninitialized value in concatenation (.) or string at -e line 7.
x: , y: 42
$y ist package-global, $x nicht.
QuoteDie Beispiele von ptk und pq sollte man einmal unter 'use strict' laufen lassen - dann wird der dortige Gedankenfehler klarer ...
bitte...
tina@tuxedo:~> perl -Mstrict -wle'
my $x;
BEGIN {
$x = 1234;
}
warn $x;'
1234 at -e line 6.
tina@tuxedo:~>