Say I want to declare a function whose parameter is an array of strings:
sub process-string-array(Str[] stringArray) # invalid
{
...
}
How would I do that ?
A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name.
To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.
Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.
It depends on the sigil you want to use:
sub process-string-array(Str @array) { ... } # @-sigil
sub process-string-array(Array[Str] $array) { ... } # $-sigil
Note that you have to be careful to pass in a declared Str array to do this which means adhoc arrays will need to passed in with a typed declaration:
my Str @typed-array = <a b c>;
process-string-array <a b c>; # errors
process-string-array @typed-array; # typed array in
process-string-array Array[Str].new: <a b c>; # adhoc typed array
If you don't want to deal with typing arrays like this, you can use a where
clause to accept any Any
-typed array that happens to include only Str
elements (which is often easier to use IME):
sub process-string-array(@array where .all ~~ Str) { ... }
This, however, (as jnthn reminds in the comments) requires type checking each element (so O(n) perf versus O(1) ), so depending on how performance sensitive things are, it may be worth the extra code noise. Per Brad's suggestion, you could multi
it, to speed things up when the array is typed and fallback to the slower method when not.
multi sub process-string-array(Int @array) {
... # actual processing here
}
multi sub process-string-array(@array where .all ~~ Str) {
process-string-array Array[Int].new: @array
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With