Today, I saw an article about passing references in parameters. I mentioned a problem. I have encountered it before, but I used other methods to bypass it.
You can solve this problem by passing parameter references. So I plan to write it down. Hope to help you.
I will directly reference the example in this book.
If we pass two arrays in the parameter, some problems will occur.
Sub getarrays {
My (@ A, @ B) = @_;
.
.
}
@ Fruit = QW (Apples oranges banana );
@ Veggies = QW (carrot cabbage turnip );
Getarrays (@ fruit, @ veggies );
The above code is expected to assign @ fruit to @ A and @ veggies to @ B, but the result is not the same.
When getarrays (@ fruit, @ veggies) is called, the parameter @ fruit and @ veggies are compressed into a single array.
In this way, inside the getarrays function, @ _ is assigned to @ A, that is, @ fruit and @ veggies are assigned to @.
We cannot know when an array ends or when the next array starts, because we only know @_.
In this case, passing parameter references can solve this problem. That is, we do not need to pass the entire array, as long as the reference of the relevant array is passed.
Sub getarrays {
My ($ fruit_ref, $ veg_ref) = @_;
.
.
}
@ Fruit = QW (Apples oranges banana );
@ Veggies = QW (carrot cabbage turnip );
Getarrays (// @ fruit, // @ veggies );
The getarrays () function always receives two values, that is, two references, no matter how long these references point to the array. At this time,
$ Fruit_ref and $ veg_ref can be used to display or edit data, as shown below:
Sub getarrays {
My ($ fruit_ref, $ veg_ref) = @_;
Print "fruit:", join (',', @ $ fruit_ref );
Print "veggies:", join (',', @ veggies_ref );
}
When you pass a reference to a scalar, array, or hash structure as a parameter to a function, there are several issues to remember.
When you pass a reference, the function can operate on the raw data pointed to by the reference.
Therefore, we should pay attention to this when using references.