On Sat, Sep 20, 2003 at 03:56:14PM +0530 Ramprasad A Padmanabhan wrote: > I have a script in which I am using foreach in two diff ways > I am doing a last; in the very first loop So each time the variable $t > should be assigned only once. > > But you can see the results dont match. > > > #!/usr/bin/perl > use strict; > use warnings; > > my @alpha = qw(a b c d ); > my $t=""; > foreach ( @alpha ){ > $t=$_; > last; > } > > print "Value of t is '$t'\n"; > # OUTPUT: Value of t is 'a' > > $t=""; > foreach $t ( @alpha ){ > last; > } > print "Value of t is '$t'\n"; > # OUTPUT: Value of t is '' > > exit 0; > > > Not that it is a big problem for me , In my actual script I just have > avoided the second format and my problem is solved. But the puzzle is, > How does $t get reset in the foreach
The answer is in 'perldoc perlsyn': The "foreach" loop iterates over a normal list value and sets the vari- able VAR to be each element of the list in turn. If the variable is preceded with the keyword "my", then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with "my", it uses that variable instead of the global one, but it's still localized to the loop. The last sentence is important here: Even though $t is a lexical variable in your program, it's value is nonetheless localized inside the loop and regains its previous value when leaving it. Tassilo -- $_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({ pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#; $_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]