On Thu, Apr 2, 2009 at 07:06, Joseph Mwesigwa Bbaale
<[email protected]> wrote:
> Hello,
>
> I am a complete beginner - no programming background.
> I want to begin with Perl and I decided to by Randal's book "*Learning Perl*".
> I seem to have been progressing smoothly till when I arrived at the code
> below on page 65.
>
> my @names = qw/ tom fred dan betty roy /;
> my $result = &which_element_is("dan" @names);
>
> sub which_element_is {
> my($what, @array) = @_;
> foreach (0..$#array) {
> if ($what eq $array[$_]) {
> return $_;
> }
> }
> -1;
> }
>
> The author states or seems to imply that, "... *...@array* is a copy of
> *...@names
> *"! But I don't understand how and why this is so.
> I am stuck.
> Please, can someone help and explain to me how and why *...@array* is a copy
> of
> *...@names?
snip
You can copy one array into another like this:
my @first_array = (1, 2, 3, 4);
my $second_array = @first_array;
The array @second_array will contain (1, 2, 3, 4). It is important to
note that this is a copy, so if you where to say
$first_array[0] = 5;
The array @first_array would contain (5, 2, 3, 4), but @second_array
would be unaffected and therefore would still contain (1, 2, 3, 4).
You can also use list assignment with scalar variables:
my @array = (1, 2, 3);
my ($x, $y, $z) = @array;
In this case $x will be 1, $y will be 2, and $z will be 3. You can
also mix scalars and an array so long as the array goes last:
my @first_array = (1, 2, 3, 4, 5, 6, 7);
my ($x, $y, $z, @second_array) = @array;
Here $x will be 1, $y will be 2, $z will be 3 and @second_array will
be (4, 5, 6, 7).
Now, when you call a function in Perl the items you hand to the
function get put in the special array @_, so if you have a function
sub foo {
print "first arg is $_[0], second arg is $_[1]\n";
}
and you say
foo("abcd", 55);
the program will print "first arg is abcd, second arg is 55\n". We
can see that the function in the sample code is being called with
("dan", @names). At the time of the call @names contains ("tom",
"fred", "dan", "betty", "roy"). This means that inside the function
@_ will be ("dan", "tom", "fred", "dan", "betty", "roy"). Which means
when
my($what, @array) = @_;
executes $what get become "dan" and @array get become ("tom", "fred",
"dan", "betty", "roy").
I hope this helps, please ask for clarifications if you need them.
--
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/