Re: reference/alias in perl vs reference/alias in C++
grocery_stocker <cdalten@gmail.com> wrote in news:25dad38d-0e82-4c19-
b9c2-f6a198a2be35@q24g2000prf.googlegroups.com:
On May 23, 10:48 am, grocery_stocker <cdal...@gmail.com> wrote:
How are references and aliases in perl different than references in
aliases in C++?
And going off on a tanget, given something like
#!/usr/bin/perl -w
use warnings;
is in general preferable to -w.
You forgot:
use strict;
# global array definition
Useless comment (it is also wrong).
my @array = ("a","b","c");
my @array = qw( a b c ); # easier on the eyes
sub print_array {
foreach my $element (@array) {
$element .= "9";
print $element . "\n";
}
}
for ($i = 0; $i < 3; $i++) {
&print_array();
}
First off, omit the & unless you know and desire its specific effect in
this case.
How would I prevent $elment from modifying @array?
$element is not modifying anything. $element is an alias to the current
element of @array. The statement you wrote
$element .= "9";
is modifying the contents of @array in each iteration of the loop.
The easiest way to avoid modifying the contents of @array would be for
you not to modify the contents of the array.
The name print_array is simply bad. The subroutine does not just print
the contents of the array but prints some modification of the elements
of the array.
Depending on what you actually want to do, there are many different ways
of writing such a subroutine (each of which is infinitely better than
what you wrote).
Some examples below. Some of these are sillier than the others.
#!/usr/bin/perl
use strict;
use warnings;
my @array = qw( a b c d e f g h i j k l );
my %hash = @array;
print "${_}9\n" for @array;
print map { "${_}9\n" } @array;
print_with_suffix( 9 => \@array );
print_with_suffix2( 9 => @array, \@array, \%hash );
sub print_with_suffix {
my ($suffix, $array_ref) = @_;
return unless ref $array_ref eq 'ARRAY';
print "${_}$suffix\n" for @$array_ref;
}
sub print_with_suffix2 {
my $suffix = shift;
for my $arg ( @_ ) {
if ( ref $arg eq 'ARRAY' ) {
print_with_suffix( $suffix, $arg );
}
elsif ( ref $arg eq 'HASH' ) {
print_with_suffix( $suffix, [ values %$arg ] );
}
else {
print "$arg$suffix\n";
}
}
}
__END__
--
A. Sinan Unur <1usa@llenroc.ude.invalid>
(remove .invalid and reverse each component for email address)
comp.lang.perl.misc guidelines on the WWW:
http://www.rehabitation.com/clpmisc/