Click here to get back home

reference/alias in perl vs reference/alias in C++

 HomeNewsGroups | Search | About
 comp.lang.perl.misc    Post an article   get this group's latest topics as an RSS feed add this group's latest topics to your My MSN content add this group's latest topics to your My Yahoo content
Subject Author Date
reference/alias in perl vs reference/alias in C++ grocery_stocker 05-23-2008
Posted by Jürgen Exner on May 23, 2008, 6:35 pm
Please log in for more thread options
[...]
>my @array = ("a","b","c");
[...]
> foreach my $element (@array) {
> $element .= "9";
[...]
>How would I prevent $elment from modifying @array?

$element doesn't modify anything. If at all it is modified by the
assignment and because it is an alias to to each @array element those
are modified, too.

Solution: just create a copy:
my @array = ("a","b","c");
[...]
foreach (@array) {\
        my $element = $_ # create copy instead of aliasing
$element .= "9";

jue

Posted by Tad J McClellan on May 24, 2008, 11:15 am
Please log in for more thread options

[ There is no C/C++ in this sub-question.
Newsgroups: modified.
]



> #!/usr/bin/perl -w

#!/usr/bin/perl
use warnings;
use strict;

> # global array definition
> my @array = ("a","b","c");
>
> sub print_array {

my @array = @_; # a different array, named the same as the 1st (outer) one

> foreach my $element (@array) {
> $element .= "9";
> print $element . "\n";
> }
>
> }
>
> for ($i = 0; $i < 3; $i++) {
> &print_array();

print_array(@array);

> }
>
> How would I prevent $elment from modifying @array?


See above.

See also:

perldoc -q "difference between calling"

"Coping with Scoping":

http://perl.plover.com/FAQs/Namespaces.html


--
Tad McClellan
email: perl -le "print scalar reverse qq/moc.noitatibaher0cmdat/"

Similar ThreadsPosted
PERL to mean what 'perldoc perl' says is wrong? (was: Re: perl should be improved and perl6) April 14, 2008, 11:37 pm
FAQ 3.0: What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? October 31, 2004, 12:03 pm
FAQ 3.0 What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? February 2, 2005, 12:03 pm
FAQ 2.18 What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? March 28, 2005, 12:03 am
FAQ 2.18 What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? June 12, 2005, 11:03 am
FAQ 2.18 What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? August 29, 2005, 10:03 pm
FAQ 2.18 What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? October 28, 2005, 10:03 pm
FAQ 2.18 What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? December 25, 2005, 5:03 am
FAQ 2.17 What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? January 8, 2006, 11:03 pm
FAQ 2.18 What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? January 16, 2006, 11:03 pm

Our other projects:

Art Dolls, Fairies and Mermaids - Sunnyfaces.net

Roy's Linux, Programming and Search Engines messages

1-Script XML SitemapXML Sitemap