Reputation: 159
what is the meaning that alias passed an array parameter in perl? Is right the following code?
#!/usr/bin/perl
@myarray = (1, 2, 3, 4, 5);
&my_sub(@myarray);
sub my_sub {
my (@subarray) = @_;
print @subarray;
}
Upvotes: 0
Views: 194
Reputation: 57640
The term alias describes that multiple names can point to the same data, without the syntactic restriction of references.
In Perl, aliases can be created arbitrarily by e.g. Data::Alias
, but there are a few constructs that create aliases themself.
The foreach-loop. The current element is an alias to the original element in the list:
my @array = 1 .. 5;
for my $elem (@array) {
$elem++; # $elem is an alias to $array[$i]
}
# the @array is now 2 .. 6.
Subroutine arguments. Perl subroutines are called with a flat list of scalars (i.e. collections like hashes or arrays get flattened into this list). This list is accessible via the @_
array. All elements in this array are aliases to the parameters.
sub alias_increment {
for my $elem (@_) {
$elem++;
}
}
my @array = 1 .. 5;
alias_increment(@array);
# array now is 2 .. 6.
Do note that in this example, @_
is not an alias to @array
, but $_[$i]
is an alias to $array[$i]
.
Using these aliases allows you to have out-arguments, but that makes for akward APIs imho.
You should also note that Perl usually has copying semantics. This means that the statement $foo = $bar
usually copies the data of $bar
to $foo
. The copy is a seperate entity, and if the original was an alias, the copy won't be an alias itself. When copying in list context, all elements are copied. This means that
my @array = @_;
does the same thing as
my @array;
$array[0] = $_[0];
# ...
This breaks all aliasing.
This is in fact used as a pattern in Perl to do “call by value” and allows to limit side-effects of subroutines.
Upvotes: 0
Reputation:
This code:
sub my_sub {
my (@subarray) = @_;
print @subarray;
}
Makes a copy of the array that was passed into the subroutine. This is correct if you want to modify the array in your subroutine without modifying the original array.
The correct way to call a subroutine in modern Perl is just my_sub(@myarray);
. You should not use &
.
Upvotes: 1