in reply to Re: Preserve array contents in for() loop
in thread Preserve array contents in for() loop

The first part of your advice is rock solid: If you don't want to modify the content of the element of the array you're iterating over, knowing that the iterant is an alias to that element, don't modify it. It's kind of like when the patient goes to the doctor and says, "It hurts when I press here.", and the doctor replies, "Don't press there." This is simply what aliasing means, and covered in perlsyn.

However, you're wrong about just giving an array to Data::Dumper. Run the following snippet:

use strict; use warnings; use Data::Dumper; my @array = qw/This That Other/; print Dumper @array; print Dumper \@array;

The POD for Data::Dumper has the following two important statements:

Given a list of scalars or reference variables, writes out their contents in perl syntax.

....And later on...

Due to limitations of Perl subroutine call semantics, you cannot pass an array or hash. Prepend it with a \ to pass its reference instead. This will be remedied in time, now that Perl has subroutine prototypes. For now, you need to use the extended usage form, and prepend the name with a * to output it as a hash or array.

++ to your post though, aliases do modify the element they're aliased to, if you modify the value of the alias. In fact, if the list being iterated over is a literal list (not an array variable), you can't even modify the alias's value. So if the intent is to preserve the original content of the array, just don't go modifying the alias's value.


Dave

Replies are listed 'Best First'.
Re^3: Preserve array contents in for() loop
by punkish (Priest) on Sep 21, 2004 at 15:24 UTC
    Thanks Dave. I am learning more and more that all possible Perl questions have already been answered... one just has to read the docs.

    That said, I guess I use Dumper so much that I didn't even notice what it was saying to me...

    #!/usr/bin/perl # test.pl use strict; use Data::Dumper; my @foo = ('a', 'b', 'c');

    When I run the above, I get...

    > test.pl $VAR1 = 'a'; $VAR2 = 'b'; $VAR3 = 'c';
    I didn't even notice that it was reporting each variable separately and not as a part of an array.

    I go looking for trees, and forget that I am in a forest.