[Athens-pm] Perl oddities
Mark Pors
mark at dreamzpace.com
Thu Nov 14 04:06:57 CST 2002
Giorgos Epitidios wrote:
>Good morning everybody. Yesterday I spoke about not being able to have one
>foreach loop inside another. That was wrong. What you cannot do is play
>with the $_ variable inside a loop (if you want to keep your array elements
>intact). See the following example:
>
>sub func {
> $_ = 100;
>}
>
>
>my @array = (1,2,3);
>
>print "before calling func\n";
>foreach ( @array ) {
> print "$_\n";
>}
>print "calling func inside loop\n";
>foreach ( @array ) {
> print "$_\n";
> func;
>}
>print "after calling func\n";
>foreach ( @array ) {
> print "$_\n";
>}
>
>What you get by running it is:
>
>before calling func
>1
>2
>3
>calling func inside loop
>1
>2
>3
>after calling func
>100
>100
>100
>
>As someone mentioned in the comp.lang.perl forum:
>
> Little known features of foreach. The iteration variable used
> in the foreach is not a copy, but in fact an alias to the value,
> in this case $_. Thus, when you change it you change the value
> in the array.
>
>So actually $_ IS each element of the array. This means that &func changes
>the array elements.
>
>Hope that is of interest to someone.
>
>
>Giorgos Epitidios
>
>P.S. My mistakes make me wiser
>
>
:-)
this is why I do:
foreach $arr_value ( @array )
It's not as perly as foreach ( @array ), but a bit more clear (and safe)
Mark
>
>_______________________________________________
>Athens-pm mailing list
>Athens-pm at mail.pm.org
>http://mail.pm.org/mailman/listinfo/athens-pm
>
>
>
>
More information about the Athens-pm
mailing list