go ahead... be a heretic | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
Actually it's not too difficult to fix your problem, and I can point out the issue along the way.
First, you should understand that in your first example, the loop is iterating over the actual scalar variables, $name, $nerd, $noodle, $froodle. And $item is aliasing (or "is a") those scalars. When you change $item, via the substitution, you change value of the variable that it represents; being $name, $nerd, $noodle, and $froodle, depending on the iteration of the loop. In your second example, you are assigning the values contained in the scalar variables $name, $nerd, $noodle, and $froodle, to an array named @look_for. But what that means is that @look_for just contains a list of values, not a list of scalar variables. So in your second example, when you iterate over each element contained in @look_for, $item becomes an alias for $look_for[0], in the first iteration, $look_for[1] in the second iteration, etc. And as you recall, those elements contain the values that were passed to them by $name, $nerd, etc. The distinction is that at this point, $name, $nerd, and so on, are no longer associated, in any way, with @look_for. The result is that as you change $item in the second example, you're changing the value of elements of @look_for, not the value of the variables $name, and so on. If you intend to use the second example, you need to give @look_for references to the scalar variables $name, $nerd, $noodle, and $froodle, instead of just the values. That way, each element of @look_for refers to the original scalar variables. Then, inside the loop, you must dereference $item to change the value of the scalar variable referenced by the array element $item aliases. Here is a working example:
Now you'll find that you're modifying the value of the original scalar variables pointed to (in C-speak) or referred to (in Perl-speak) by the elements in @look_for. Just remember to always dereference the elements in @look_for when you mean to modify the values of the variables they point to. I hope this is helpful. I recommend reading the perldoc on references, and on lists of lists, as both will aid you in understanding how this works. Dave "If I had my life to do over again, I'd be a plumber." -- Albert Einstein In reply to Re: array confusion
by davido
|
|