pritesh_ugrankar has asked for the wisdom of the Perl Monks concerning the following question:
Hi,
Is it ok to declare a common loop variable if I want to iterate through multiple arrays?
use warnings; use strict; my @arr1 = qw (this will print for sure); my @arr2 = qw (this is second array); my $things = "nothing"; foreach $things (@arr1) { print "$things\n"; }; print "$things\n"; foreach $things (@arr2) { print "$things\n"; }; print "$things\n";
I am using "nothing" just to verify if it gets reset to it's original value and do understand that "nothing" is a string, and has "nothing" to do (pun unintended) with undef or empty.
So this will be a single copy of loop variable used for multiple arrays. My question is, is this considered ok in Perl? or am I to have a seperate loop variable for each of the arrays? Even if I have the same name for the loop variable, the following two $things are different right?
use warnings; use strict; my @arr1 = qw (this will print for sure); my @arr2 = qw (this is second array); foreach my $things (@arr1) { print "$things\n"; }; foreach my $things (@arr2) { print "$things\n"; };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: declaring a common loop variable
by poj (Abbot) on Feb 28, 2017 at 12:12 UTC | |
|
Re: declaring a common loop variable
by haukex (Archbishop) on Feb 28, 2017 at 12:02 UTC | |
|
Re: declaring a common loop variable
by 1nickt (Canon) on Feb 28, 2017 at 13:25 UTC | |
|
Re: declaring a common loop variable
by AnomalousMonk (Archbishop) on Feb 28, 2017 at 22:24 UTC | |
|
Re: declaring a common loop variable
by pritesh_ugrankar (Monk) on Feb 28, 2017 at 13:04 UTC | |
|
Re: declaring a common loop variable
by pritesh_ugrankar (Monk) on Feb 28, 2017 at 14:08 UTC |