Perl Programming Lists and Arguments in Perl |
Lists Are One Dimensional Recall that all lists and all arrays are one dimensional. If we have this list: (@a, @b) it becomes a one-dimensional list containing the contents of@afollowed by the contents of@b. This is an important rule when it comes to passing arrays into functions, since they will be passed in as a one-dimensional list. This is illustrated in the following example: #!/usr/bin/perl -w use strict; my(@nums1, @nums2); process_arrays(@nums1, @nums2); sub process_arrays { print "contents of \@a\n"; print "contents of \@b\n"; This program creates two 3-element arrays,@nums1and@nums2. These arrays are then passed intoprocess_arrays()and are immediately copied into two arrays,@aand@b. We might think that@areceives the contents of@nums1and@breceives the contents of@nums2, but that is not what happens. Since the arguments are passed in as process_arrays(@nums1, @nums2); the elements are flattened into this one-dimensional list: (2, 4, 6, 8, 10, 12) and this list is passed in and assigned to the assignable list: my(@a, @b) = @_; Since this assignable list contains an array,@a, it will consume all the elements that are assigned to it. Therefore,@bwill be empty because there are no elements remaining to assign to it. So, when we execute this program, we will see that@acontains all the elements passed in and@bcontains no elements: $ perl passarrays.pl contents of @b $ Later, when we discuss references in Chapter 11, we will see how to pass two arrays (or hashes) into a function and treat them as two separate variables.
blog comments powered by Disqus |
|
|
|
|
|
|
|