Perl Monk, Perl Meditation | |
PerlMonks |
Re^2: Comparing two arraysby GrandFather (Saint) |
on Feb 21, 2015 at 03:55 UTC ( [id://1117395]=note: print w/replies, xml ) | Need Help?? |
is really bad because the two instances of $var are not the same animal. The recommended code is:
The problem is that the first version of the code makes it look like the $var declared before the for loop is the one used in the loop and might even retain the last value it was assigned in the loop. It's not and it doesn't. The loop variable ($var in the sample code) is an alias for each value looped over. In some sense it's not a real variable at all! To see the alias in action try:
Did you notice that the array values were altered! $var becomes each array element in turn. What you do to $var you do to the current array element. For the vast majority of Perl code you aren't aware of this aliasing trick. Sometimes it is really useful and sometimes, if you don't know about it, it is really nasty. The same thing happens in map and grep where the default variable $_ is aliased in turn to each list element processed. Aside from all that, don't declare multiple variables on a single line. As a general thing it's a clue that you are declaring things in the wrong place, and if it's the right place the declaration is important enough that it should be one variable per line. Along with choosing good variable names, managing variable scope (and therefore where variables are declared) are important parts of good programming style.
Perl is the programming world's equivalent of English
In Section
Seekers of Perl Wisdom
|
|