I used this function to find values in an array for a while but I'd like to improve it:
# Checks if the first argument is found in the subsequent ones.
function my_function_is_value_in() {
local -r NEEDLE=$1
local -ra HAYSTACK=( "${@:2}" )
local value
for value in "${HAYSTACK[@]}"; do
[[ $value == "$NEEDLE" ]] && return 0
done
return 1
}
I now think the assignment to the "parameter renaming for readability" array HAYSTACK is inefficient, especially for a "search" function, potentially run many times as so:
my_function_is_value_in coconut cherry coriander coconut cottage-cheese
Does Bash have an efficient way to do the above or is looping through ${@:2} directly as efficient as this can get?
Compare/contrast with perl's grep( /pattern/ @array).. that's a dedicated function to do exactly this.
perl'sgrep function is not efficient for this task. It iterates through the entire array, even if the first element was a match. Never use perl'sgrepin boolean context, useList::MoreUtils::any.