Thread abgedrehtes problem mit switch: oder bin ich blind? (71 answers)
Opened by deepblack at 2004-06-16 21:56

pq
 2004-07-07 17:23
#83485 #83485
User since
2003-08-04
12209 Artikel
Admin1
[Homepage]
user image
[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.
Quote
Ergo:
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:
Code: (dl )
1
2
3
4
5
6
7
8
9
10
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.
Quote
Die Beispiele von ptk und pq sollte man einmal unter 'use strict' laufen lassen - dann wird der dortige Gedankenfehler klarer ...

bitte...
Code: (dl )
1
2
3
4
5
6
7
8
tina@tuxedo:~> perl -Mstrict -wle'
my $x;
BEGIN {
$x = 1234;
}
warn $x;'
1234 at -e line 6.
tina@tuxedo:~>
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. -- Damian Conway in "Perl Best Practices"
lesen: Wiki:Wie frage ich & perlintro Wiki:brian's Leitfaden für jedes Perl-Problem

View full thread abgedrehtes problem mit switch: oder bin ich blind?